Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; namespace YourNamespace { public static class HtmlExtensions { public static MvcHtmlString RadioButtonForEnum&lt;TModel, TProperty&gt;( this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression ) { var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); var names = Enum.GetNames(metaData.ModelType); var sb = new StringBuilder(); foreach (var name in names) { var id = string.Format( "{0}_{1}_{2}", htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, metaData.PropertyName, name ); var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString(); sb.AppendFormat( "&lt;label for=\"{0}\"&gt;{1}&lt;/label&gt; {2}", id, HttpUtility.HtmlEncode(name), radio ); } return MvcHtmlString.Create(sb.ToString()); } } } </code></pre> <p>You could also enforce a <a href="http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx" rel="noreferrer">generic constraint to an enum type</a> for this helper method.</p> <p>and then:</p> <p>Model:</p> <pre><code>public enum ActionStatus { Open, Closed } public class MyViewModel { public ActionStatus Status { get; set; } } </code></pre> <p>Controller:</p> <pre><code>public class HomeController : Controller { public ActionResult Index() { return View(new MyViewModel { Status = ActionStatus.Closed }); } [HttpPost] public ActionResult Index(MyViewModel model) { return View(model); } } </code></pre> <p>View:</p> <pre><code>@model MyViewModel @using (Html.BeginForm()) { @Html.RadioButtonForEnum(x =&gt; x.Status) &lt;input type="submit" value="OK" /&gt; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload