johndoe
johndoe

Reputation: 65

Remote Validation in ASP.NET MVC 3

I am trying to get remote validation working in ASP.NET MVC 3 but for some reason the validation never gets fired. I am returning json from the controller and in FireFox it ask me to download the files. Not sure what is going on here. Here is my code:

@using(Html.BeginForm(new {Action = "ValidateUserName"})) {

<text> Enter UserName: </text> @Html.TextBoxFor(x => x.UserName) 

<input type="submit" value="Login" />  



}

Here is the RegistrationViewModel:

 public class RegistrationViewModel
    {
        [Required(ErrorMessage = "UserName is required!")]
        [Remote("ValidateUserName","Home",ErrorMessage ="UserName already taken!")]
        public string UserName { get; set; }
    }

And here is the HomeController:

  public ActionResult ValidateUserName(RegistrationViewModel registrationViewModel)
        {
            return Json(!registrationViewModel.UserName.Equals("test"),JsonRequestBehavior.AllowGet); 

        }

Upvotes: 0

Views: 294

Answers (1)

OakRaven13
OakRaven13

Reputation: 21

A couple of things to consider:

1) In your view, you should be referencing the jquery validation and unobtrusive javascript libraries:


    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

2) Also in your view, you should have an Html.ValidationMessageFor(m => m.Attribute):


    @Html.ValidationMessageFor(x => x.UserName)

3) Lastly, make sure you have the two AppSettings in your web.config file that enable the client-side validation.


    <appSettings>
        <add key="ClientValidationEnabled" value="true"/>
        <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    </appSettings>

Upvotes: 2

Related Questions