在我的 MVC 应用程序中,我创建了一个助手,它应该从模型中获取一个枚举,然后显示该类型的所有其他可用枚举的单选按钮。
例如,您有枚举 SatusActive, Inactive, Closed和页面的模型,Status = Status.Active因此您希望显示Inactive和的单选按钮Closed。
继续这个例子,MVC 视图调用助手 RadioButtonForEnum:
@Html.RadioButtonForEnum(model => model.Status)
RadioButtonForEnum 然后获取该类型的所有枚举列表并将它们打印为单选按钮;但是,我不确定如何获取传递的枚举以将其排除在外names
public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> 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("<label for=\"{1}\">{0}{2}</label>", radio, id, HttpUtility.HtmlEncode(StringHelpers.PascalCaseToSpaces(name)));
    }
    return MvcHtmlString.Create(sb.ToString());
}