我有一个视图,模型有一个项目的集合。然后我有一个EditorFor模板,该模板负责为用户创建一个下拉列表,为集合中的每个项目选择一个有限数量的值:
@model Consultants.Models.ProgramSkill <tr> <td>@Model.Program.Name </td> <td>@Model.Program.Category </td> <td> @Html.DropDownListFor( model => model.Level,new SelectList(new[] { 0,1,2,3,4,5 },Model.Level)) </td> </tr>
但是我宁愿让radiobutton做同样的事情,那可能在MVC 3?如果是这样,怎么办?
解决方法
这将是一个自定义html助手的完美候选人:
using System.Web.Mvc; using System.Web.Mvc.Html; using System.Text; using System.Collections.Generic; using System.Linq.Expressions; using System; public static class HtmlExtensions { public static MvcHtmlString RadioButtonListFor<TModel,TProperty>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel,TProperty>> ex,IEnumerable<SelectListItem> values) { string name = ExpressionHelper.GetExpressionText(ex); var sb = new StringBuilder(); int counter = 1; foreach (var item in values) { sb.Append(htmlHelper.RadioButtonFor(ex,item.Value,new { id = name + counter.ToString()})); var label = new TagBuilder("label"); label.SetInnerText(item.Text); label.Attributes.Add("for",name + counter.ToString()); sb.Append(label.ToString()); counter++; } return MvcHtmlString.Create(sb.ToString()); } }
模型:
public class Myviewmodel { public IEnumerable<SelectListItem> Items { get; set; } public string Level { get; set; } }
控制器:
public class HomeController : Controller { public ActionResult Index() { var model = new Myviewmodel { Level = "2",Items = Enumerable.Range(1,5).Select(x => new SelectListItem { Value = x.ToString(),Text = "item " + x }) }; return View(model); } }
和视图:
@model AppName.Models.Myviewmodel @using (Html.BeginForm()) { @Html.RadioButtonListFor(x => x.Level,Model.Items) <input type="submit" value="OK" /> }