2013-12-13 24 views
2

我有我的asp.net VMC Web应用程序内的下列模型类: -无法引用Url.content我的模型视图模型类中

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;

回答

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") 
+0

工作得很好,非常感谢。 –

相关问题