我正在尝试创建一个强类型的单选按钮列表。我不知道如何从 HtmlExtensionClass 中的 ModelMetaData 中获取操作列表?动作列表通过 Index 动作中的 MyViewmodel 传入。
助手类 c#
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonForList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression
)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
//var actions = metaData.ModelType; //? how can i get my list of actions in here?
var sb = new StringBuilder();
foreach (var action in actions)
{
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
action
);
var radio = htmlHelper.RadioButtonFor(expression, action, new { id = id }).ToHtmlString();
sb.AppendFormat(
"<label for=\"{0}\">{1}</label> {2}",
id,
HttpUtility.HtmlEncode(action),
radio
);
}
return MvcHtmlString.Create(sb.ToString());
}
}
控制器索引动作
public ActionResult Index()
{
List<PageAction> actionslist = new List<PageAction>();
actionslist.Add(new PageAction() { action = "View" });
actionslist.Add(new PageAction() { action = "Edit" });
actionslist.Add(new PageAction() { action = "Create" });
return View(new MyViewModel
{
actions = actionslist
});
}
public class PageAction
{
public string user { get; set; }
public string action { get; set; }
}
public class MyViewModel
{
public List<PageAction> actions { get; set; }
}
看法
@model radioButtonlist.Models.MyViewModel
@using radioButtonlist.Models;
@using (Html.BeginForm())
{
@Html.RadioButtonForList(x => x.actions)
}