checkbox and radio button editor templates in mvc 4

using UIHint Editor Templates render checkbox and radio button. 


Create RadioButtonList.cshtml in Views > Shared > EditorTemplates
@model long?
@using System.Collections
@using System.Web.Mvc;
@{
    var list = (List<SelectListItem>)ViewData["List"];
}
<ul style="list-style: none; margin: 0 0 0px 20px;">
    @foreach (var item in list)
    {
        <li style="padding: 0px;">
            @{
        var radioId = ViewData.TemplateInfo.GetFullHtmlFieldId(item.Value);
        var checkedClass = (item.Value == Model.ToString() ? "checked" : string.Empty);
                <input type="radio" 
                       id="@radioId" 
                       name="@ViewData.TemplateInfo.HtmlFieldPrefix" 
                       value="@item.Value" 
                       @checkedClass />
                <label for="@radioId">@item.Text</label>
            }
        </li>
    }
</ul>

Create CheckBoxList.cshtml in Views > Shared > EditorTemplates
@model long?
@using System.Collections
@using System.Web.Mvc;
@{
    var list = (List<SelectListItem>)ViewData["List"];
}
<ul style="list-style: none; margin: 0 0 0px 20px;">
    @foreach (var item in list)
    {
        <li style="padding: 0px;">
            @{
        var radioId = ViewData.TemplateInfo.GetFullHtmlFieldId(item.Value);
        var checkedClass = (item.Value == Model.ToString() ? "checked" : string.Empty);
                <input type="checkbox" 
                       id="@radioId" 
                       name="@ViewData.TemplateInfo.HtmlFieldPrefix" 
                       value="@item.Value" 
                       @checkedClass />
                <label for="@radioId">@item.Text</label>
            }
        </li>
    }
</ul>
Now Call in Model Class
[UIHint("CheckBoxList")]
[Required]
[Display(Name = "Working Day")]
public string WorkingDay { get; set; }

[UIHint("RadioButtonList")]
[Required]
[Display(Name = "Gender")]
public string Gender { get; set; }

Full Demo Download
checkbox and radio button editor templates in mvc 4 checkbox and radio button editor templates in mvc 4 Reviewed by Bhaumik Patel on 7:32 PM Rating: 5