如何向我的自定义 HtmlHelper 添加验证消息?

发布于 2024-12-09 02:53:10 字数 1733 浏览 1 评论 0原文

我有一个使用数据注释的类:

[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”中硬编码了“Missing”这个词。如何获取我在数据注释中所述的文本?

I have a class where I have used data annotations:

[Required(ErrorMessage = "You must indicate which sex you are.)]
public string Sex { get; set; }

I have also created a custom HtmlHelper called RadioButtonListFor, which I can call like this:

@Html.RadioButtonListFor(m => m.Sex, "SexList")

My SexList is defined like this:

IList<string> SexList = new List() { "Male", "Female"};

And below is the RadioButtonListFor extension (not totally finished yet):

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);
    }
}

My problem is this: Right now I have hardcoded the word "Missing" in the attribute "data-val-required". How do I get the text I stated in my data annotations?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幼儿园老大 2024-12-16 02:53:10

啊...在睡个好觉后我自己找到了解决方案:-)

用以下内容替换 RadioButtonListFor:

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");

        var validationAttributes = helper.GetUnobtrusiveValidationAttributes(prefix);

        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);
            foreach (KeyValuePair<string, object> pair in validationAttributes)
            {
                tag.MergeAttribute(pair.Key, pair.Value.ToString());
            }
            txt += tag.ToString(TagRenderMode.Normal);
            txt += item;
        }

        return helper.Raw(txt);
    }

基本上我添加了“validationAttributes”,它显然是我的验证项的字典。循环遍历这些并添加它们使其工作起来就像一个魅力!

2011 年 10 月 13 日编辑:

最终得到以下解决方案。我决定发送一个字典,其中键是单选按钮值,字典的值是单选按钮文本,而不是仅仅获取字符串列表。

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";

        // find existing value - if any
        string value = helper.ViewData.Eval(prefix) as string;

        var validationAttributes = helper.GetUnobtrusiveValidationAttributes(prefix);
        string txt = string.Empty;

        // create hidden field for error msg/value
        TagBuilder tagHidden = new TagBuilder("input");
        tagHidden.MergeAttribute("type", "hidden");
        tagHidden.MergeAttribute("name", prefix);
        tagHidden.MergeAttribute("value", value);
        tagHidden.MergeAttribute("id", prefix.Replace('.', '_'));
        foreach (KeyValuePair<string, object> pair in validationAttributes)
        {
            tagHidden.MergeAttribute(pair.Key, pair.Value.ToString());
        }
        txt += tagHidden.ToString(TagRenderMode.Normal);

        // prepare to loop through items
        int index = 0;
        var items = helper.ViewData.Eval(list) as IDictionary<string, string>;
        if (items == null)
            throw new NullReferenceException("Cannot find " + list + "in view data");

        // create a radiobutton for each item. "Items" is a dictionary where the key contains the radiobutton value and the value contains the Radiobutton text/label
        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("value", item.Key);
            if (item.Key == value)
                tag.MergeAttribute("checked", "true");
            tag.MergeAttribute("onclick", "javascript:" + tagHidden.Attributes["id"] + ".value='" + item.Key + "'");
            txt += tag.ToString(TagRenderMode.Normal);
            txt += item.Value;
        }

        return helper.Raw(txt);
    }

Ah... found the solution myself, after a good nights sleep :-)

Replacing the RadioButtonListFor with the below:

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");

        var validationAttributes = helper.GetUnobtrusiveValidationAttributes(prefix);

        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);
            foreach (KeyValuePair<string, object> pair in validationAttributes)
            {
                tag.MergeAttribute(pair.Key, pair.Value.ToString());
            }
            txt += tag.ToString(TagRenderMode.Normal);
            txt += item;
        }

        return helper.Raw(txt);
    }

Basically I have added "validationAttributes" which apparently is a dictionary of my validation items. And looping through these and adding them makes it work like a charm!

Edited October 13th 2011:

Ended up with the below solution. Instead of just getting a list of strings, I decided to send in a Dictionary where the key is the radiobutton value and the value of the dictionary is the radiobutton text.

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";

        // find existing value - if any
        string value = helper.ViewData.Eval(prefix) as string;

        var validationAttributes = helper.GetUnobtrusiveValidationAttributes(prefix);
        string txt = string.Empty;

        // create hidden field for error msg/value
        TagBuilder tagHidden = new TagBuilder("input");
        tagHidden.MergeAttribute("type", "hidden");
        tagHidden.MergeAttribute("name", prefix);
        tagHidden.MergeAttribute("value", value);
        tagHidden.MergeAttribute("id", prefix.Replace('.', '_'));
        foreach (KeyValuePair<string, object> pair in validationAttributes)
        {
            tagHidden.MergeAttribute(pair.Key, pair.Value.ToString());
        }
        txt += tagHidden.ToString(TagRenderMode.Normal);

        // prepare to loop through items
        int index = 0;
        var items = helper.ViewData.Eval(list) as IDictionary<string, string>;
        if (items == null)
            throw new NullReferenceException("Cannot find " + list + "in view data");

        // create a radiobutton for each item. "Items" is a dictionary where the key contains the radiobutton value and the value contains the Radiobutton text/label
        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("value", item.Key);
            if (item.Key == value)
                tag.MergeAttribute("checked", "true");
            tag.MergeAttribute("onclick", "javascript:" + tagHidden.Attributes["id"] + ".value='" + item.Key + "'");
            txt += tag.ToString(TagRenderMode.Normal);
            txt += item.Value;
        }

        return helper.Raw(txt);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文