Reputation: 1
I have the following model class inside my asp.net vmc web application :-
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/");
}
}
but i am unable to reference the Url.content
in my last line of code, although i have included the using System.Security.Policy;
Upvotes: 2
Views: 736
Reputation: 38478
You need to write an extension method UrlHelper class then:
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;
}
}
Also don't use HttpContext.Current
if you don't have to. You can use it in your view like this:
@Url.ImageOrDefault("somefile")
Upvotes: 2