gpt4 book ai didi

asp.net-mvc - 带有资源文件的模型的单选按钮枚举助手

转载 作者:行者123 更新时间:2023-12-02 22:18:35 25 4
gpt4 key购买 nike

问题:

需要绑定(bind)一个强类型模型,该模型具有一个枚举属性 Gender。我也喜欢显示资源文件中的显示文本。

我的模型是

public enum GenderViewModel
{
[Display(Name = "Male", ResourceType = typeof(Resources.Global), Order = 0)]
Male,
[Display(Name = "Female", ResourceType = typeof(Resources.Global), Order = 1)]
Female

}

最初,我尝试关注 http://romikoderbynew.com/2012/02/23/asp-net-mvc-rendering-enum-dropdownlists-radio-buttons-and-listboxes/

但它有点复杂,我无法随心所欲地更正我的 HTML。

然后我从stackoverflow看了看简单易行的实现,pass enum to html.radiobuttonfor MVC3

并在 cshtml 中使用了一个 HtmlHelper,如下所示

@Html.RadioButtonForEnum(m => m.Gender)

生成的 HTML

<label for="_Gender_Male">
<input type="radio" value="Male" name="Gender" id="_Gender_Male"
data-val-required="Gender is required" data-val="true" checked="checked">
<span class="radiotext">Male</span>
</label>

<label for="_Gender_Female">
<input type="radio" value="Female" name="Gender" id="_Gender_Female">
<span class="radiotext">Female</span></label>

It really simple and works well for me. But i am not getting values from Resource files. My application is multilingual and I use a Global Resource file for different language support.

问题:

Male 显示应为 ManFemale 显示应为 Kvinna 应该来自资源文件,因为我当前的文化是 sv-se

任何人都可以帮助/提供一个简单的解决方案,它可以很好地控制 HTML 吗?

最佳答案

您所要做的就是适应 my original helper以便它考虑到 DisplayAttribute:

public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
if (!metaData.ModelType.IsEnum)
{
throw new ArgumentException("This helper is intended to be used with enum types");
}

var names = Enum.GetNames(metaData.ModelType);
var sb = new StringBuilder();

var fields = metaData.ModelType.GetFields(
BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
);

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();
var field = fields.Single(f => f.Name == name);
var label = name;
var display = field
.GetCustomAttributes(typeof(DisplayAttribute), false)
.OfType<DisplayAttribute>()
.FirstOrDefault();
if (display != null)
{
label = display.GetName();
}

sb.AppendFormat(
"<label for=\"{0}\">{1}</label> {2}",
id,
HttpUtility.HtmlEncode(label),
radio
);
}
return MvcHtmlString.Create(sb.ToString());
}
}

现在,如果您用 DisplayAttribute 装饰了一些枚举值,这些值将来自资源文件。

关于asp.net-mvc - 带有资源文件的模型的单选按钮枚举助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14103206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com