【问题标题】:How do I use the ASP.NET MVC ValidationMessage HTML Helper inside my own custom helper?如何在我自己的自定义助手中使用 ASP.NET MVC ValidationMessage HTML Helper?
【发布时间】:2009-12-17 16:46:20
【问题描述】:

我正在尝试创建一个自定义 HTML Helper 来封装一些表示逻辑,因为我必须在同一页面上多次重用此逻辑,并且可能在将来。

如果用户的地址在北美,那么我希望为电话号码输入显示两个文本框,一个用于区号,另一个用于其余号码。如果地址不在北美,那么我想要一个用于显示完整号码的文本框。

以下代码按预期工作以输出正确的文本框,但是,一旦我添加了与每个文本框关联的验证,我现在就会收到从 ValidationMessage Helper 调用的 ToString() 调用引发的 NullReferenceException (ValidationMessage 助手返回一个空值!!)。

public static string TelephoneNumberInputListItem(this HtmlHelper helper,
                                         string country,
                                         string northAmericanAreaCodeFormName,
                                         string northAmericanAreaCode,
                                         string northAmericanRemainingNumberFormName,
                                         string northAmericanRemainingNumber,
                                         string internationalFullNumberFormName,
                                         string internationalFullNumber)
    {

        //set up the error message and styling
        object errorHtmlAttributes = new { @class = "fError" };
        string validationMessage = "*";

        object htmlAttributes;

        //start building our list item tag which includes our telephone number 
        //input and validation controls
        TagBuilder listItemBuilder = new TagBuilder("li");

        //determine based on the country specified if this should be a North 
        //American phone input form or an international one
        if (isNorthAmericanCountry(country))
        {
            //add the text input controls
            htmlAttributes = new { size = 3, maxlength = 3 };
            listItemBuilder.InnerHtml = helper.TextBox(northAmericanAreaCodeFormName, northAmericanAreaCode, htmlAttributes).ToString();

            htmlAttributes = new { size = 7, maxlength = 7 };
            listItemBuilder.InnerHtml += helper.TextBox(northAmericanRemainingNumberFormName, northAmericanRemainingNumber, htmlAttributes).ToString();

            //Add the Validation Message controls
            listItemBuilder.InnerHtml += helper.ValidationMessage(northAmericanAreaCodeFormName, validationMessage, errorHtmlAttributes).ToString();
            listItemBuilder.InnerHtml += helper.ValidationMessage(northAmericanRemainingNumberFormName, validationMessage, errorHtmlAttributes).ToString();
        }
        else
        {
            //add the text input control
            htmlAttributes = new { size = 15, maxlength = 15 };
            listItemBuilder.InnerHtml = helper.TextBox(internationalFullNumberFormName, internationalFullNumber, htmlAttributes).ToString();

            //Add the Validation Message control
            listItemBuilder.InnerHtml += helper.ValidationMessage(internationalFullNumberFormName, validationMessage, errorHtmlAttributes).ToString();
        }

        return listItemBuilder.ToString(TagRenderMode.Normal);
    }

您能帮我添加验证,以便这些输入文本框仍然是调用视图中发生的整体表单验证的一部分吗?我应该提一下,将 TextBox 和 ValidationMessage Helper 直接放在 View 中可以正常工作。

使用 HTML Helpers 有很多嗡嗡声(“如果有 IF,请使用帮助程序”任何人?),但是如果我们不能向我们使用的输入控件添加验证控件,我们应该如何使用它们.

提前感谢您的帮助。

【问题讨论】:

    标签: asp.net-mvc validation html-helper


    【解决方案1】:

    如果相应的模型状态中没有指示错误,则 ValidationMessage 帮助器返回 null。请参阅下面的实际代码...

    由于 ValidationMessage 帮助器返回一个字符串,因此没有理由调用 ToString()(这是导致异常的原因)。删除 ToString,您的代码应该可以按预期工作。

    您也可以从 TextBox 帮助器中删除您的 ToString 调用。

    public static string ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage, IDictionary<string, object> htmlAttributes) {
      if (modelName == null) {
        throw new ArgumentNullException("modelName");
      }
    
      if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName)) {
        return null;
      }
    
      ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
      ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
      ModelError modelError = ((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors[0];
    
      if (modelError == null) {
        return null;
      }
    
      TagBuilder builder = new TagBuilder("span");
      builder.MergeAttributes(htmlAttributes);
      builder.MergeAttribute("class", HtmlHelper.ValidationMessageCssClassName);
      builder.SetInnerText(String.IsNullOrEmpty(validationMessage) ? GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState) : validationMessage);
    
      return builder.ToString(TagRenderMode.Normal);
    }
    

    【讨论】:

    • 感谢 mkedobbs 澄清当 ModelState 中没有错误时 ValidationMessage Helper 返回 null。删除 ToString() 确实解决了我的问题,但我首先将它放在那里的原因是因为助手返回类型 MVCHtmlString,我无法通过强制转换将其转换为字符串。但是,不知何故,将此 MVCHtmlString 连接到另一个字符串(在我的情况下使用 += 运算符)成功地将其转换为字符串,因此问题解决了。
    猜你喜欢
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    相关资源
    最近更新 更多