如何在 mvc 视图中检查文件结果是否为空
我有一个如下的控制器方法,用于将图像发送到 MVC 视图以
public FileResult ShowImage(GuidID)
{
DataServiceClient client = new DataServiceClient ();
AdviserImage result;
result = client.GetAdviserImage(ID);
return File(result.Image, "image/jpg" );
}
在我的视图中显示,我正在使用它
<img src="<%= Url.Action("ShowImage", "Adviser", new { ID = Model.AdviserID }) %>" alt="<%:Model.LicenceNumber %>" />
来显示图像
,但某些 id 没有图像并返回 null,我想检查文件结果是否为 null view ,如果其为 null 则不显示图像。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将需要另一个单独的控制器操作来检查数据存储并返回
ContentResult
,该结果将为true
或false
(或您想要的其他字符串)来判断 ID 是否有字节),然后在视图中您将需要这个:另一个选项是您有一个包含对图像字节的引用的视图模型。这样,您就可以在控制器中为视图(父模型)准备模型,并在那里提取图像的字节,然后在视图中您将拥有:
ImageBytes
属性的类型为byte[]
例如,这是我的观点之一的片段:
HTH
You will need another, separate controller action that checks the datastore and returns
ContentResult
which will be eithertrue
orfalse
(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: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:
with
ImageBytes
property being of typebyte[]
For instance, this is a snippet from one of my views:
HTH
为什么不在控制器中检查 null 并将逻辑保留在显示之外:
您可以创建默认图像并将其设为静态。如果您确实不想显示图像,则创建一个 Html 扩展方法以将逻辑保留在视图之外:
Why not check for null in your controller and leave the logic out of the display:
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: