我想创建封装了一些表示逻辑的自定义HTML帮助程序,因为我必须在同一页面上重复使用此逻辑几次,并可能在将来。如何在我自己的自定义帮助器中使用ASP.NET MVC ValidationMessage HTML帮助器?
如果用户的地址在北美,那么我需要为电话号码输入显示两个文本框,一个用于区号,另一个用于号码的其余部分。如果地址在北美之外,那么我希望显示一个单一的文本框以显示完整的号码。
下面的代码正常工作,用于输出正确的文本框,但是,只要我添加了与每个文本框相关的验证,我现在就从ValidationMessage Helper上的ToString()调用中引发了NullReferenceException调用(ValidationMessage Helper返回null!)。
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直接放入视图中可以正常工作。
对于使用HTML Helpers(“如果存在IF,使用助手”任何人?)有很多嗡嗡声,但是如果我们无法将验证控件添加到输入控件,我们应该如何使用它们。使用。
非常感谢您的帮助。
谢谢mkedobbs澄清,当ModelState中没有错误时,ValidationMessage Helper返回null。删除ToString()确实可以解决我的问题,但我之所以首先使用它的原因是因为助手返回类型MVCHtmlString,我无法通过强制转换将其转换为字符串。但不知何故,将这个MVCHtmlString连接到另一个字符串(在我的情况下使用+ =运算符)将其成功转换为字符串,因此解决了问题。 – FullOfQuestions 2009-12-17 19:07:04