6 c# asp.net-mvc default web-config imagesource
我有一个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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的视图中,您可以使用以下内容制作网址:
<img src="<% Html.ImageUrlFor("~/content/images/myfolder/myimage.jpg"); %>" />
Run Code Online (Sandbox Code Playgroud)
编辑: 正如吉姆指出的那样,我还没有真正解决尺寸问题.我个人使用自动大小请求管理/大小这是另一个故事,但如果你担心文件夹/大小只是传递信息来构建路径.如下:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的视图中,您可以使用以下内容制作网址:
<img src="<% Html.ImageUrlFor("myimage.jpg", ImageSizeFolderEnum.Small); %>" />
Run Code Online (Sandbox Code Playgroud)
如果文件夹是一个固定的集合,建议使用Enum以获得更好的编程控制,但是为了快速而讨厌的方法,如果文件夹是db生成的话,不能仅仅使用字符串.
| 归档时间: |
|
| 查看次数: |
6595 次 |
| 最近记录: |