I have created the ImageFor HtmlHelper for use
if the image url is stored in a database, web.config etc.
Helper:
using
System.Linq.Expressions;
using
System.Web.Routing;
namespace
System.Web.Mvc
{
public static
class
HtmlHelpers
{
public static
MvcHtmlString ImageFor<TModel, TProperty>(
this HtmlHelper<TModel>
htmlHelper,
Expression<Func<TModel,
TProperty>> expression)
{
var imgUrl = expression.Compile()(htmlHelper.ViewData.Model);
return BuildImageTag(imgUrl.ToString(),
null);
}
public static
MvcHtmlString ImageFor<TModel, TProperty>(
this
HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel,
TProperty>> expression,
object htmlAttributes)
{
var imgUrl = expression.Compile()(htmlHelper.ViewData.Model);
return BuildImageTag(imgUrl.ToString(),
htmlAttributes);
}
private static
MvcHtmlString BuildImageTag(string
imgUrl, object htmlAttributes)
{
TagBuilder tag =
new TagBuilder("img");
tag.Attributes.Add("src", imgUrl);
if (htmlAttributes !=
null)
tag.MergeAttributes(new
RouteValueDictionary(htmlAttributes));
return
MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
}
}
Usage:
In this example, the image url is stored in the web.config in appSettings.
<appSettings>
<add
key="ImageUrl"
value="/Content/CSSiteLogo.gif"/>
</appSettings>
Create a property in the model for the image url.
public
class
IndexModel
{
public string
ImageUrl { get; set;
}
}
Fetch the image url from the web.config and pass the model to the View in the
Action method.
public
ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
IndexModel model =
new IndexModel
{ ImageUrl = WebConfigurationManager.AppSettings["ImageUrl"]
};
return View("Index",
model);
}
In the View, use the ImageFor helper.
@Html.ImageFor(model
=> model.ImageUrl, new { width="216px",
height="70px", alt="some
alt text" })
OR
@Html.ImageFor(model
=> model.ImageUrl)
Result:

shervin salimianPosted Jun 5, 2018, 12:13 AM
My problem has solved but i cant see image and i have new problem" could not load the image" plz help me
shervin salimianPosted Jun 5, 2018, 12:00 AM
Hi shantanu.tank u for your article.i have an error"Severity Code Description Project File Line Category Source Suppression State ToolError CS1061 'HtmlHelper<CS_Car>' does not contain a definition for 'ImageFor' and no extension method 'ImageFor' accepting a first argument of type 'HtmlHelper<CS_Car>' could be found (are you missing a using directive or an assembly reference?)" can you help me plz? "
Yohan DufilsPosted Jan 13, 2016, 9:48 AM
Hello ! Very great code ! Thanks !Improvement Suggestion : For HTML Attributes, use the line : tagBuilder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); This will make UnderScore to be changed into Hyphen (useful for data-toggle or data-placement attributes). Futhermore, I prefer this way to close img tag : return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));