开发者

how to check the file result is null within the mvc view

开发者 https://www.devze.com 2023-03-29 07:24 出处:网络
I have a controller method as below to send an image to a MVC view to display public FileResult ShowImage(GuidID)

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(I开发者_Python百科D);


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


Why not check for null in your controller and leave the logic out of the display:

result = client.GetAdviserImage(ID);
if (result == null)
{
    result = AdviserImage.Missing;
}

You can create a default image and make it static. If you really don't want to display the image then create an Html extension method to keep the logic out of the view:

public static string AdviserImage(this HtmlHelper helper, AdviserImage image, int id, int lic)
{
    if (image != null)
    {
        string url = string.Format("/Adviser/ShowImage/{0}", id);
        string html = string.Format("<img src=\"{0}\" alt=\"{1}\" />", url, image.lic);
        return html;
    }
    return string.Empty; // or other suitable html element
}
0

精彩评论

暂无评论...
验证码 换一张
取 消