asp.net mvc 3 - ajax form submit and validation

25,259

Solution 1

I've been using malsup's jQuery form plugin for a while for this purpose. I'm honestly not familiar with AjaxHelper, but does look like it'll do what you're looking for. As far as doing both client and server side validation, that should all happen mostly automatically as long as you're using model binding and the attributes from the System.DataAnnotations namespace.

public class MyModel
{
    [Required(ErrorMessage = "Please enter your name")]
    public String Name { get; set; }

    [Required(ErrorMessage = "Please enter your email")]
    public String Email { get; set; }

    [Required(ErrorMessage = "Please enter a rating")]
    [Range(1, 5, ErrorMessage = "The rating must be between 1 and 5")]
    public Int32 Rating { get; set; }
}

[HttpPost]
public ActionResult Index(MyModel myModel)
{
   if(ModelState.IsValid)
   {
       // good to go, put it in the DB or whatever you need to do
   }
   else 
   {
       return View(model); // return the user back to the page, ModelState errors can be viewed using Html.ValidationSummary() or individual Html.ValidationMessageFor() calls
   }
}

If you're doing your own custom server-side validation, you can either create your own custom validation attribute by creating an attribute that implements ValidationAttribute, or just add validation errors by calling ModelState.Errors.Add() (or something around there, I don't have a reference handy)

For client side, MVC will generate clientside validation for you based on the DataAnnotations attributes on your model.

Solution 2

MVC.NET 3 already has this out of the box. Just make sure to have ClientValidationEnabled enabled in the web.config. Check this

Share:
25,259
santiagoIT
Author by

santiagoIT

Updated on May 05, 2020

Comments

  • santiagoIT
    santiagoIT almost 4 years

    I am sorry if this has been asked already, but I have been looking for sometime but all I have found are rather old posts (mvc1, mvc2). I have a form which I would like to submit via Ajax.

    This looks like it would work but does not cover server side validation.

    1) I am unsure if I should use the AjaxHelper.BeginForm or use raw jquery calls ($.ajax)? What is the recommended approach here?

    2) How do I handle client and server side validation? I am hoping the mvc framework provides a built in mechanism for dealing with this? There are some validations which I am only doing server side. Would using a ValidationSummary still work here?

    I am using asp.net mvc3/razor with unobtrussive javascript validation.

    Thank you!

    Edit: (as requested by Bobby B below). This was added months after asking the question as a user wanted to know how to use AjaxHelper

    This is the javascript code I used:

    <script type="text/javascript">
    
    function ajaxValidate() {
      return $('form').validate().form();
    }
    
    function getGbPostSuccess(ajaxContext){
      // .... it is not necessary to do anything here.
    }
    function showFaliure(ajaxContext){
       // handle failure
    }
    

    HTML snippet:

    @using (Ajax.BeginForm("Index", "Home", new AjaxOptions
                            {
                                UpdateTargetId = "form1",
                                InsertionMode = InsertionMode.Replace,
                                OnBegin = "ajaxValidate",
                                OnSuccess = "getGbPostSuccess",
                                OnFailure = "showFaliure"
                            }))
    {
    
  • santiagoIT
    santiagoIT about 13 years
    I checked out the link, but it explains how to enable client side validation. I do have client side validation enabled, that is unfortunately not my question.
  • santiagoIT
    santiagoIT about 13 years
    Thank you! I have it working now. I ended up using AjaxHelper.
  • Bobby B
    Bobby B about 13 years
    Any chance you could elaborate on how you used AjaxHelper? I'm facing the same issue myself and I'm trying to decide what the best approach to take is. Thanks!
  • santiagoIT
    santiagoIT almost 13 years
    I will add the example code at as an edit to the question. That way I can format it better ;-)