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

Posted by Maxim Z. on Stack Overflow See other posts from Stack Overflow or by Maxim Z.
Published on 2010-05-08T21:51:20Z Indexed on 2010/05/08 21:58 UTC
Read the original article Hit count: 295

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.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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET