无法在模型视图模型类中引用Url.content

时间:2013-12-13 23:45:49

标签: c# asp.net asp.net-mvc-4

我的asp.net vmc Web应用程序中有以下模型类: -

    public static class HtmlHelperExtensions
    {
        public static string ImageOrDefault(this HtmlHelper helper, string filename)
        {
            var imagePath = uploadsDirectory + filename + ".png";
            var imageSrc = File.Exists(HttpContext.Current.Server.MapPath(imagePath))
                               ? imagePath : defaultImage;

            return imageSrc;
        }

        private static string defaultImage = "/Content/uploads/virtual-data-center.png";
        private static string uploadsDirectory = Url.Contnet("/Content/uploads/");
    }
}

但我无法在我的最后一行代码中引用Url.content,尽管我已经包含了using System.Security.Policy;

1 个答案:

答案 0 :(得分:2)

您需要编写一个扩展方法UrlHelper类:

public static class HtmlHelperExtensions
{
    private static string defaultImage = "/Content/uploads/virtual-data-center.png";

    public static string ImageOrDefault(this UrlHelper urlHelper, string fileName)
    {
        var imagePath = urlHelper.Content("/Content/uploads/") + fileName + ".png";

        HttpContextBase httpContext = urlHelper.RequestContext.HttpContext;
        var imageSrc = File.Exists(httpContext.Server.MapPath(imagePath))
                           ? imagePath : defaultImage;

        return imageSrc;
    }
}

如果不需要,也不要使用HttpContext.Current。你可以在你的视图中使用它:

@Url.ImageOrDefault("somefile")