Wednesday, July 11, 2012

MVC: Htmlhelper. Make the markup clean

This is a quick post, mostly for myself, to remember a great concept of HtmlHelper in MVC.

Since, I have never worked before with MVC, I am really pleased to see how web pages look much cleaner in MVC than in ASP.Net Web forms.

One way to achieve cleanness in the asp.net page is to use HtmlHelper class from System.Web.Mvc
instead of standard HTML markup.

Here is a quick example:

You want to show the picture in your page. The old way to do it:
@foreach (var item in Model)
{
     @: Review
     <div class ="review">
     <h4>@item.Restaurant.Name</h4>
     <img src=" item.Restaurant.ImageUrl" alt="item.Restaurant.Nam " />    
     </div>
}


This approach will add more markups in you page + you will need to get rid of the automated encoding of the string inside that code block.

Here is a nicer way to go:

@foreach (var item in Model)
{
     @: Review
     <div class ="review">
     <h4>@item.Restaurant.Name</h4>
     @Html.Image(item.Restaurant.ImageUrl, item.Restaurant.Name)
     </div>
}

     
Wait a minute, there is no method HtmlHelper.Image.... 
Here is a perk, do your own extension for HtmlHelper:

 public static class MyHelpers
    {
        public static MvcHtmlString Image (this HtmlHelper helper,string src, string AltText)
        {
           
            var builder = new TagBuilder("img");
            builder.MergeAttribute("src", src);
            builder.MergeAttribute("alt", AltText);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
    }