Santosh Mishra
Santosh Mishra

Reputation: 33

Remote Validation in MVC3

I am performing Remote Validation in ASP.NET MVC3,but its not working means it not calling the action as I am seeing in Chrome java script Console.Here is my Code: Model:

public class Genre
    {
        public int GenreId { get; set; }
        [Remote("GenreNameExist","Genre",ErrorMessage="Genre name already Exists!!!")]
        public string Name { get; set; }
        public String Description { get; set; }
        public List<Album> Albums { get; set; }
    }

Controller:

public ActionResult GenreNameExist(Genre genre) 
        {
             var gen = db.Genres.Where(x=>x.Name==genre.Name).FirstOrDefault();
            if (gen == null)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else {

                return Json(string.Format("{0} is not available.", Name), JsonRequestBehavior.AllowGet);
            }
        }

and View:

@Html.ValidationSummary(true);
    <div class="editor-label">
        @Html.LabelFor(x => x.Name)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(x => x.Name)
        @Html.ValidationMessageFor(x=>x.Name)
    </div>

Thanks in Advance!!!

Upvotes: 0

Views: 94

Answers (1)

Lasse Edsvik
Lasse Edsvik

Reputation: 9298

You need to add:

var gen = db.Genres.Where(x=>x.Name==Name).FirstOrDefault();

so it will execute.

In the controller pass the class Genre so it maps to that class and then add if(ModelState.IsValid) so it'll perform validation against that class. Or add a ViewModel class.

Update:

Do you have the scripts in the right order?

<script src="/Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

Upvotes: 1

Related Questions