加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何显示在Asp.net MVC中找不到的图像

发布时间:2020-12-15 08:38:08 所属栏目:百科 来源:网络整理
导读:我有一个asp.net mvc项目.在一个特殊的视图中,我在我的proect中调用来自不同不同文件夹的四个图像. 有时无法找到图像.我想为每个文件夹设置一个图像,因为所有4个文件夹包含不同大小的图像,所以我需要为每个文件夹设置特定大小的图像. 当图像找不到任何方法时
我有一个asp.net mvc项目.在一个特殊的视图中,我在我的proect中调用来自不同不同文件夹的四个图像.

有时无法找到图像.我想为每个文件夹设置一个图像,因为所有4个文件夹包含不同大小的图像,所以我需要为每个文件夹设置特定大小的图像.

当图像找不到任何方法时,我怎么能显示默认图像.i表示当目录没有我在视图中调用的图像时调用none.png.

他们是在没有找到图像的情况下显示图像的任何方式.

任何方式在asp.net 4 MVC 3中使用web.config或设置其他任何东西.

解决方法

最简单的方法是使用html帮助程序.请注意在显示图像文件名之前检查文件系统的额外性能.虽然命中率很小,但除非你的流量非常高,否则你不会发现任何问题.然后,您可以实现某种缓存,以便应用程序“知道”文件是否存在.

您可以使用自定义html帮助程序

public static class ImageHtmlHelpers
{
   public static string ImageUrlFor(this HtmlHelper helper,string contentUrl)
   {
       // Put some caching logic here if you want it to perform better
       UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
       if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(contentUrl)))
       {
           return urlHelper.Content("~/content/images/none.png");
       }
       else
       {
           return urlHelper.Content(contentUrl);
       }
   }
}

然后在您的视图中,您可以使用以下内容制作网址:

<img src="<% Html.ImageUrlFor("~/content/images/myfolder/myimage.jpg"); %>" />

编辑:正如吉姆指出的那样,我还没有真正解决尺寸问题.我个人使用自动大小请求管理/大小这是另一个故事,但如果你担心文件夹/大小只是传递信息来构建路径.如下:

public static class ImageHtmlHelpers
{
   public static string ImageUrlFor(this HtmlHelper helper,string imageFilename,ImageSizeFolderEnum imageSizeFolder)
   {
       UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
       string contentUrl = String.Format("~/content/userimages/{0}/{1}",imageSizeFolder,imageFilename);
       if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(contentUrl)))
       {
           return urlHelper.Content(String.Format("~/content/userimages/{0}/none.png",imageSizeFolder));
       }
       else
       {
           return urlHelper.Content(contentUrl);
       }
   }
}

然后在您的视图中,您可以使用以下内容制作网址:

<img src="<% Html.ImageUrlFor("myimage.jpg",ImageSizeFolderEnum.Small); %>" />

如果文件夹是一个固定的集合,建议使用Enum以获得更好的编程控制,但是为了快速而讨厌的方法,如果文件夹是db生成的话,不能仅仅使用字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读