James Ray Anderson

James Ray Anderson
James Ray Anderson
0 comments

Radio Button List for MVC 4 RadioButtonList(For)

10:36 AM
RadioButtonList(For) is a custom extension of the Microsoft MVC Framework's HtmlHelper class which creates a postable model-based list of radio buttons.

Features:
  • Strongly-typed, based on view model
  • Customizable layout and appearance through CSS
  • Vertical (default) or Horizontal (through CSS)
  • Include or exclude a label
  • Selectable value
  • Open source
How to Get It
Use the source code below. 

public static MvcHtmlString RadioButtonListFor<TModel, TProperty>( 
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression, 
            IEnumerable<SelectListItem> listOfValues,
            string cssClass = "",
            bool includeLabel = true,
            string selectedItemValue = "")

        {             
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); 
            var sb = new StringBuilder();

            if (listOfValues != null) 
            {                 
                // Create a radio button for each item in the list 
                foreach (SelectListItem item in listOfValues) 
                {                     
                    // Generate an id to be given to the radio button field 
                    var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
                    object htmlAttrib = new { id = id };

                    if (selectedItemValue == item.Value) htmlAttrib = new { id = id, @checked = "checked" };

                    // Create and populate a radio button using the existing html helpers 
                    var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text)); 
                    var radio = htmlHelper.RadioButtonFor(expression, item.Value, htmlAttrib).ToHtmlString();

                    if (includeLabel == false)
                        label = null;

                    // Create the html string that will be returned to the client 
                    // e.g. <input data-val="true" data-val-required="You must select an 
                    // option" id="TestRadio_1" name="TestRadio" type="radio" value="1" />
                    // <label for="TestRadio_1">Line1</label> 
                    sb.AppendFormat("<div class=\"" + cssClass + "\">{0}{1}</div>", radio, label); 

                } 
            }            
            return MvcHtmlString.Create(sb.ToString()); 
        } 

Depends on:
  • System
  • System.Web
  • System.Web.Mvc
  • System.Web.Mvc.Html
  • System.Linq
  • System.Linq.Expressions
  • System.Text
  • System.Collections.Generic

Original Article by Jon Lanceley
http://jonlanceley.blogspot.com/2011/06/mvc3-radiobuttonlist-helper.html

0 comments:

 
Toggle Footer
Top