Problem with Client-Side Validation in MVC 2

 

[Note: This post applies to ASP.NET MVC 2, Preview 2.0]

Today while doing the demo for the previous post, I ran into an issue where the Javascript code for the client-side validation (the call to EnableClientValidation ) was not being output during the form rendering.

Take a look at the following two snippets:

First:

    <% Html.BeginForm();%>
 
        <%=Html.EditorForModel() %>
            <p>
                <input type="submit" value="Save" />
            </p>
    <% Html.EndForm(); %>

 

Second:

  <% using (Html.BeginForm()) {%>
 
        <%=Html.EditorForModel() %>
            <p>
                <input type="submit" value="Save" />
            </p>
    <% } %>

 

See the difference? The latter is using the using statement. In my previous post I’m using this option and all works well. However, if you go with the first option, the Javascript call will not be output. The reason for this (after debugging the source) is that the call to make this happen takes place in the Dispose method of the MvcForm. Explicitly calling Html.EndForm won’t cause this to take place.

I’ve talked to Mathew from the QA team, and he’s confirmed it’s a known issue. I think the output of the JS code should ideally be decoupled from the form construction. For instance, If I were to use a manual form tag, this wouldn’t work either [I’ve haven’t given it that much thought either].

In the meantime, if you want client-side validation, make sure you use the second option.

3 thoughts on “Problem with Client-Side Validation in MVC 2

  1. Matthew Osborn

    This is known that ClientValidation will only be output when Dispose is called. This is how we know that the form is done. You can continue to use Begin and End form so long as you call dispose which after all is best practice.

    Reply
  2. Hadi Hariri

    @Mathew,

    But in all fairness, if you need to know when the form is done, you could would assume that an explicit call to EndForm would tell you that.

    Reply
  3. Steve Strong

    Although I agree that calling Dispose() may be best practice, I would also expect that calling EndForm() would do the same thing. As an analogy, consider FileStreams – I would not expect to have to call Dispose() on a FileStream if I’ve explicitly called Close().

    If you really need Dispose() to be called, then there should not be an EndForm() method at all. Having both and having them do different things is, I think, confusing.

    Cheers,

    Steve

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s