Extension of a verified RadioButtonList and mvcradiobuttonlist under ASP. NET MVC
In ASP. NET MVC4, HtmlHelper provides the Html. RadioButton () method for us to display the Radio Button. To display a group of single-choice buttons, you can traverse a set to display each single-choice button. This article tries to write an extension method to display a set of radio buttons with verification.
First, expand HtmlHelper. The extension method receives a set of SelectListItem, traverses this set, and displays each single-choice button, so that these single-choice buttons have different id attribute values.
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc.Html;
namespace System.Web.Mvc
{
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> list)
{
// Obtain metadata
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
if (list != null)
{
foreach (var item in list)
{
// Concatenate the attribute name and the Value of the Set element as the element id.
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
// Create a radio button
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new {id = id}).ToHtmlString();
sb.AppendFormat("<div class=\"RadioButton\">{0}{1}</div>", radio, label);
}
}
return MvcHtmlString.Create(sb.ToString());
}
}
}
Assume that there is a View Model, and one of the attributes must be.
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class Vm
{
[Required (ErrorMessage = "Required")]
public int CityId { get; set; }
}
}
The following City classes are used as data sources for all Radio buttons.
namespace MvcApplication1.Models
{
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
}
In HomeController, an Action method is provided to convert the City set to the SelectListItem set and pass it to the view.
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
List<City> cities = new List<City>()
{
New City () {Id = 1, Name = "Qingdao "},
New City () {Id = 2, Name = "Jinan "},
New City () {Id = 3, Name = "leveling "}
};
ViewData["c"] = from c in cities
select new SelectListItem() {Text = c.Name, Value = c.Id.ToString()};
return View(new Vm());
}
[HttpPost]
public ActionResult Index(Vm vm)
{
if (ModelState.IsValid)
{
return Content(vm.CityId.ToString());
}
else
{
return View(vm);
}
}
}
}
In _ Layout. csthml, you must have a client to verify js.
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
In Home/Index. chtml, use the extended method to display the Radio Button group.
@model MvcApplication1.Models.Vm
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<style type="text/css">
.RadioButton { float:left; }
</style>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new {id = "addForm"}))
{
@Html.RadioButtonListFor(v => v.CityId, ViewData["c"] as IEnumerable<SelectListItem>)
@Html.ValidationMessageFor(v => v.CityId)
<br/><br/>
<Input type = "submit" value = "submit"/>
}