开发者

Error with Property Validation in Form Submission in ASP.NET MVC

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.

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:

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

The error is the following:

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

My complete code for that textbox is the following:

<p>
<label for="Email">Your Email:</label>
<%=Html.TextBox("Email")%>
<%=Html.Va开发者_JAVA百科lidationMessage("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.


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

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.


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>
    <%} %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜