i'm trying to display an image in my view.
i've written an Image helper:
public static class Helpers
{
public static FileContentResult Image(this HtmlHelper htmlHelper,
byte[] imageData, string mimeType)
{
return new FileContentResult(imageData, mimeType);
}
}
myImage - is a byte array.
<img src="#Html.Image(myImage, "image/jpeg")" />
but my image is not displayed...
when i look at the source code all i see is:
<img src="System.Web.Mvc.FileContentResult">
anyone? :)
The way you are doing it you are returning the FileContentResult in between the quotes of the src="".
I see what you are trying to do, but in order for this to work, the <img src=> needs to request the URL of the image not simply put the byte[] in the src. So you'll need to set up an action method that takes in some parameter and returns the FileContentResult.
Related
Is it possible to put a HTML link in validation summary message? For example I want to put a link to another page in case there is validation error:
#Html.ValidationSummary(False, "read more")
or
#Html.ValidationSummary(False, "read " &
Html.ActionLink("more", "helpforerror").ToHtmlString)
But in the browser the tag is escaped so it doesn't form a link.
I know you have accepted an answer, but i think my solution is more simple and will require less rewriting if you want to add links to existing validation summaries.
You need to put a {0} type format item in your validation message like below, which will be replaced by your link.
ModelState.AddModelError("", "Some error message with a link here {0}.");
then in your view call your validation summary like so:
#string.Format(Html.ValidationSummary().ToString(), Html.ActionLink("Click Here", "Action_To_Link_To")).ToHtmlString()
In this case i have used an extension method I added to the string object .ToHtmlString() that basically just converts the string to an HtmlString preventing any of the markup being escaped. it looks like this:
public static HtmlString ToHtmlString(this String str)
{
return new HtmlString(str);
}
Finally I chose another way to do it: create a div containing the link etc. outside of validation summary, and add the div only if modelstate is not valid:
#If Not ViewData.ModelState.IsValid Then
#<div>read more</div>
End If
This is inspired by an answer to similar question.
The validation text is encoded before the ValidationSumary or ValidationFor, etc...
you just need tu decode the html, then create an MvcHtmlString ...
Exemple :
#HttpUtility.HtmlDecode(Html.ValidationSummary().ToString()).ToMvcHtmlString()
this is an extension i have made to make MvcHtmlString :
namespace System
{
public static class StringExtension
{
public static System.Web.Mvc.MvcHtmlString ToMvcHtmlString(this string value)
{
return System.Web.Mvc.MvcHtmlString.Create(value);
}
}
}
or you can create an HtmlHelper if you plan to reuse this:
namespace System.Web.Mvc.Html
{
public static class FormHelper
{
public static MvcHtmlString ValidationSummaryEx(this HtmlHelper htmlHelper, bool excludePropertyErrors)
{
var original = htmlHelper.ValidationSummary(excludePropertyErrors);
var decoded = HttpUtility.HtmlDecode(original.ToString());
return decoded.ToMvcHtmlString();
}
}
}
Hope it help you or future viewer.
Note: it work for all validations Summary and ValidationFor ...
No, the default behaviour doesn't allow it, but you can make your own. This is what you need: Html raw in validationsummary
You can check if form is valid by jquery and update div with link text:
<div id="divToUpdate">
</div>
$('form').submit(function(){
if(!this.valid())
$('#divToUpdate').html("read <a href='anotherpage.html'>more</a>");
});
If you're sending back HTML in the ModelStateError, you can use this one liner:
#Html.Raw(HttpUtility.HtmlDecode(Html.ValidationSummary().ToHtmlString()))
It's very similar to what #Benoit had suggested, just without needing the extension.
I have same action in a controller that fetch from db for example a Employee with a name, age, image (byte[]).
So I store the info in ViewBag. Then in the View the specific code for the image is:
<img src="#ViewBag.Image" alt="Logo" />
But when I see the content of the response I have:
<img src="System.something.FileContentResult" alt="Logo" />
I have seen a lot of examples that gets the FileContentResult from a specific Action in a Controller for example:
(The code is an example only)
public ActionResult GetEmployeeImage (int id){
byte[] byteArray = GetImageFromDB(id);
FileContentData file = new File (byteArray,"image/jpg");
return file;
}
And then render the image with:
<img src="#Url.Action("GetEmployeeImage", "Home", new { id = ViewBag.Id })" alt="Em" />
But I dont want that because I already have the image.
How can I render it to the View throw the ViewBag?
Thanks!
PD: Rendering image in a View is the same but was not concluded
One possibility is to use the data URI scheme. Bear in mind though that this will work only on browsers that support it. The idea is that you would embed the image data as base64 string into the src attribute of the img tag:
<img src="data:image/jpg;base64,#(Html.Raw(Convert.ToBase64String((byte[])ViewBag.Image)))" alt="" />
If on the other hand you want a solution that works in all browsers you will have to use a controller action to serve the image. So in the initial request fetch only the id, name and age properties of the employee and not the image. Then write a controller action that will take the employee id as parameter, query the database, fetch the corresponding image and return it as file result. Then inside the view point the src attribute of the img tag to this controller action.
Based on the answer of #darin , if any one wants to make it via calling a controller's action:
public FileContentResult GetFileByID(string ID)
{
try
{
// Get the object from the db
Ent ent = Biz.GetPatientsByID(ID);
// Convert the path to byte array (imagepath is something like: \\mysharedfolder\myimage.jpg
byte[] doc = EFile.ConvertToByteArray(ent.ImagePath);
string mimeType = File(doc, MimeMapping.GetMimeMapping(Path.GetFileName( ent.ImagePath))).ContentType;
Response.AppendHeader("Content-Disposition", "inline; filename=" + Path.GetFileName(ent.ImagePath));
return File(doc, mimeType);
}
catch (Exception ex)
{
throw ex;
}
}
In the front end:
<img id="ItemPreview" src="#Url.Action("GetFileByID","Patient", new {ID= Model.ID })" alt="" width="350" height="350" />
Where Patient is the controller name.
I'm trying to show some picture for user in a strongly typed View..
In Model members there is one that represents contents of image (ex. jpeg)
How should I pass this content to img tag to render this image?
model looks like:
publiŃ class Image {
public virtual FileContentResult currentImage { get; set; }
public Image()
{
currentImage = createSomeImage();
// createSomeImage returns new FileContentResult(bmpBytes, "image/png");
}
}
View looks like
#model app.Models.Image
<img src='#Model.currentImage' alt="" class="img" />
and I render it from parent View as:
#Html.Partial("_ImageShow", new app.Models.Image())
I've searched a lot, but found only implementations of returning image as a result of action of some controller..Is there any way to show image having fileContentResult in a View?
Thanks in advance.
In my Facebook canvas application, I want to load an image from my ASP.NET MVC Controller.
So I do somethinhg like this, in my controller (simplified):
public ActionResult GetImage(int id)
{
// ....
return File(#"c:\temp\1.jpg", "image/jpeg");
}
And it's called from my aspx page like so:
<img src="/Home/GetImage?id=20" alt="Test"/>
But the image is not displayed, I get a "red x".
So I fire up Fiddler and see that the request does indeed return the image, but the data is prepadded with Facebook's frame html:
<html><head><script type="text/javascript">
top.location = "http://www.facebook.com/dialog/oauth/?state=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&client_id=xxxxxxxxxxxxxxx&redirect_uri=http://localhost:5000/facebookredirect.axd";
</script></head><body></body></html>?????JFIF??H?H????
?ICC_PROFILE???
????????mntrRGB XYZ ?????$?acsp???????????????????????????????????
Which of course is not vaild jpeg image data.
How can I avoid this pre padded data?
Never mind, I found out myself that the signed_request data was (yet again) missing.
I thought the only way to pass this was thru a HTTP header, but (like magic) I could pass it as a parameter as well causing the request to be validated.
<img src="/Home/GetImage?id=20&signed_request=<%=Request.Params["signed_request"] %>" />
public ActionResult GetImage(int id), string signed_request)
{
var auth = new CanvasAuthorizer();
if (auth.Authorize())
{
// Indeed, I'm now authorized
return File(#"c:\temp\1.jpg", "image/jpeg");
}
/// ...
}
/M
I wish to encode my HTML sent to the browser. In my .ASPX pages I can use the <%: %> syntax. In a HTML helper of mine I try...
public static string Image(this HtmlHelper helper, string imageName, string altText)
{
return helper.Encode(String.Format("<image src='/images/{0}' alt='{1}' />", imageName, altText));
}
However, when the HTML reaches the browser the HTML just displays as text and no image is shown. How does one encode their HTML from a helper method?
remove the "helper.Encode"
public static String MyImg(this HtmlHelper helper, string imageName, string altText) {
return String.Format("<image src='/images/{0}' alt='{1}' />", imageName, altText);
}