I have a controller method as below to send an image to a MVC view to display
public FileResult ShowImage(GuidID)
{
DataServiceClient client = new DataServiceClient ();
AdviserImage result;
result = client.GetAdviserImage(ID);
return File(result.Image, "image/jpg" );
}
in my view I am using
<img src="<%= Url.Action("ShowImage", "Adviser", new { ID = Model.AdviserID }) %>" alt="<%:Model.LicenceNumber %>" />
to display the image
but some ids does not have a image and returning null, I want to check the file result is null withing the view and if its null not not to display the image.
You will need another, separate controller action that checks the datastore and returns ContentResult
which will be either true
or false
(or some other string you want to tell whether an ID has the bytes or not) and then in the view you will need this:
if(@Html.Action("action", "controller").ToString().Equals("true", StringComparison.OrdinalIgnoreCase)){
// render image tag with the call to the other action that returns FileResult
}
The other option is that you have a view model which contains a reference to the image bytes. That way you prepare the model for the view (the parent model) in the controller and pull the bytes for the image there, then in the view you would have:
if(Model.ImageBytes.Length() > 0) {
... do something
}
with ImageBytes
property being of type byte[]
For instance, this is a snippet from one of my views:
@model pending.Models.Section
@if (Model != null && Model.Image != null && Model.Image.ImageBytes.Count() > 0)
{
<a href="@Model.Url" rel="@Model.Rel">
<img title="@Model.Title" alt="@Model.Title" src="@Url.Action(MVC.Section.Actions.Image(Model.Id))" /></a>
}
HTH