Search code examples
validationasp.net-mvc-2data-annotationsclient-side-validation

Asp.Net MVC EnableClientValidation doesn't work


I want as well as Client Side Validation as Server Side Validation. I realized this as the following:

Model: ( The model has a DataModel(dbml) which contains the Test class )

namespace MyProject.TestProject
{
    [MetadataType(typeof(TestMetaData))]
    public partial class Test
    {

    }

    public class TestMetaData
    {
        [Required(ErrorMessage="Please enter a name.")]
        [StringLength(50)]
        public string Name { get; set; }
    }
}

Controller is nothing special.

The View:

<% Html.EnableClientValidation(); %>
<% using (Ajax.BeginForm("Index", "Test", FormMethod.Post, 
            new AjaxOptions {}, new { enctype = "multipart/form-data" }))
   {%>
   <%= Html.AntiForgeryToken()%>
    <fieldset>
        <legend>Widget Omschrijving</legend>
        <div>
            <%= Html.LabelFor(Model => Model.Name) %>
            <%= Html.TextBoxFor(Model => Model.Name) %>
            <%= Html.ValidationMessageFor(Model => Model.Name) %>
        </div>
    </fieldset>
    <div>
        <input type="submit" value="Save" />
    </div>
 <% } %>

To make this all work I added also references to js files:

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

Eventually it has to work, but it doesnt work 100%: It does validates with no page refresh after pressing the button. It also does "half" Client Side Validation. Only when you type some text into the textbox and then backspace the typed text. The Client Side Validation appears. But when I try this by tapping between controls there's no Client Side Validation.

Do I miss some reference or something? (I use Asp.Net MVC 2 RTM)


Solution

  • Change the order of the loaded javascript...

    <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
    

    Had the exact same problem and this cleared it up for me...