1

我正在构建的 ASP.NET MVC 站点上有一个简单的表单。此表单已提交,然后我验证表单字段不为空、为空或格式不正确。

但是,当我使用ModelState.AddModelError()我的控制器代码指示验证错误时,我在重新渲染视图时收到错误消息。在 Visual Studio 中,我得到以下行突出显示为错误的位置:

<%=Html.TextBox("Email")%>

错误如下:

用户代码未处理NullReferenceException - 对象引用未设置为对象的实例。

我对该文本框的完整代码如下:

<p>
<label for="Email">Your Email:</label>
<%=Html.TextBox("Email")%>
<%=Html.ValidationMessage("Email", "*") %>
</p>

这是我在控制器中进行验证的方式:

        try
        {
            System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(email);
        }
        catch
        {
            ModelState.AddModelError("Email", "Should not be empty or invalid");
        }

return View();

注意:这适用于我的所有字段,而不仅仅是我的电子邮件字段,只要它们是无效的

4

2 回答 2

1

这是 ASP.NET MVC 中的一个可怕的错误/功能(以任何方式调用),您可以通过像这样调用SetModelValue来修复它:

ModelState.AddModelError("Email", "Should not be empty or invalid");
ModelState.SetModelValue("Email", new ValueProviderResult("raw value", "attempted value", CultureInfo.InvariantCulture));

顺便说一句,当您可以简单地注释您的视图模型时,您是否有任何理由编写所有这些代码:

public class SomeViewModel
{
    [RegularExpression("Some bulletproof regex you could google to validate email address", ErrorMessage = "Should not be empty or invalid")]
    public string Email { get; set; }
}

并让数据活页夹完成繁重的工作。

于 2010-05-08T21:57:56.750 回答
0

我无法重现。

行动

[HttpPost]
public ActionResult Index(string email)
{
    if (string.IsNullOrEmpty(email))
    {
        ModelState.AddModelError("Email", "Should not be empty or invalid");
    }
    return View();
}

看法

    <%using (Html.BeginForm() { %>
    <p>
        <label for="Email">
            Your Email:</label>
        <%=Html.TextBox("Email")%>
        <%=Html.ValidationMessage("Email", "*") %>
        <input type="submit" />
    </p>
    <%} %>
于 2010-05-09T00:48:44.537 回答