ASP.NET MVC中的表单提交中的属性验证出错

时间:2022-01-23 15:54:43

I have a simple form on an ASP.NET MVC site that I'm building. This form is submitted, and then I validate that the form fields aren't null, empty, or improperly formatted.

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

However, when I use ModelState.AddModelError() to indicate validation errors from my controller code, I get an error when my view is re-rendered. In Visual Studio, I get that the following line is highlighted as being the location of the error:

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

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

The error is the following:

错误如下:

NullReferenceException was unhandled by user code - object reference not set to an instance of an object.

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

My complete code for that textbox is the following:

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

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

Here's how I'm doing that validation in my controller:

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

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

return View();

Note: this applies to all of my fields, not just my Email field, as long as they are invalid.

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

2 个解决方案

#1


1  

That's a horrible bug/feature (call in whatever) in ASP.NET MVC the helper that you may fix by calling SetModelValue like this:

在ASP.NET MVC中,这是一个可怕的错误/功能(无论如何调用),你可以通过调用SetModelValue来解决这个问题:

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

By the way is there any reason you would write all this code when you could simply annotate your view model:

顺便提一下,当您只是注释视图模型时,有任何理由可以编写所有这些代码:

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

and leave the data binder do the heavy lifting.

并让数据绑定器完成繁重的工作。

#2


0  

I am unable to reproduce.

我无法重现。

Action

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

View

    <%using (Html.BeginForm() { %>
    <p>
        <label for="Email">
            Your Email:</label>
        <%=Html.TextBox("Email")%>
        <%=Html.ValidationMessage("Email", "*") %>
        <input type="submit" />
    </p>
    <%} %>

#1


1  

That's a horrible bug/feature (call in whatever) in ASP.NET MVC the helper that you may fix by calling SetModelValue like this:

在ASP.NET MVC中,这是一个可怕的错误/功能(无论如何调用),你可以通过调用SetModelValue来解决这个问题:

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

By the way is there any reason you would write all this code when you could simply annotate your view model:

顺便提一下,当您只是注释视图模型时,有任何理由可以编写所有这些代码:

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

and leave the data binder do the heavy lifting.

并让数据绑定器完成繁重的工作。

#2


0  

I am unable to reproduce.

我无法重现。

Action

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

View

    <%using (Html.BeginForm() { %>
    <p>
        <label for="Email">
            Your Email:</label>
        <%=Html.TextBox("Email")%>
        <%=Html.ValidationMessage("Email", "*") %>
        <input type="submit" />
    </p>
    <%} %>