【发布时间】:2011-10-09 23:04:49
【问题描述】:
我有一个使用数据注释的类:
[Required(ErrorMessage = "You must indicate which sex you are.)]
public string Sex { get; set; }
我还创建了一个名为 RadioButtonListFor 的自定义 HtmlHelper,我可以这样调用它:
@Html.RadioButtonListFor(m => m.Sex, "SexList")
我的 SexList 是这样定义的:
IList<string> SexList = new List() { "Male", "Female"};
下面是 RadioButtonListFor 扩展(尚未完全完成):
public static class RadioButtonListForExtentions
{
public static IHtmlString RadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string list)
{
string prefix = ExpressionHelper.GetExpressionText(expression);
if (string.IsNullOrEmpty(prefix))
prefix = "empty";
int index = 0;
var items = helper.ViewData.Eval(list) as IEnumerable;
if (items == null)
throw new NullReferenceException("Cannot find " + list + "in view data");
string txt = string.Empty;
foreach (var item in items)
{
string id = string.Format("{0}_{1}", prefix, index++).Replace('.','_');
TagBuilder tag = new TagBuilder("input");
tag.MergeAttribute("type", "radio");
tag.MergeAttribute("name", prefix);
tag.MergeAttribute("id", id);
tag.MergeAttribute("data-val-required", "Missing");
tag.MergeAttribute("data-val", "true");
txt += tag.ToString(TagRenderMode.Normal);
txt += item;
}
return helper.Raw(txt);
}
}
我的问题是:现在我在属性“data-val-required”中硬编码了“缺失”这个词。如何获取我在数据注释中声明的文本?
【问题讨论】:
标签: c# .net asp.net-mvc html-helper