HOW TO USE AJAX.BEGINFORM IN ASP.NET MVC?

jayprakash sharma

Total Post:117

Points:821
Posted by  jayprakash sharma
 1478  View(s)
Ratings:
Rate this:
Is there a tutorial or code example of using Ajax.BeginForm within Asp.net MVC 3 where unobtrusive validation and Ajax exist?

This is an elusive topic for MVC 3, and I cannot seem to get my form to work properly. It will do an Ajax submit but ignores the validation errors.
  1. Kamlakar Singh

    Post:194

    Points:1396
    Re: How to use Ajax.BeginForm in Asp.Net MVC?

    Example:

    Model

    public class MyViewModel
            {
                [Required]
                public string Foo { get; set; }
            }

    Controller

    public class HomeController : Controller
            {
                public ActionResult Index()
                {
                    return View(new MyViewModel());
                }
     
                [HttpPost]
                public ActionResult Index(MyViewModel model)
                {
                    return Content("Thanks", "text/html");
                }
            }

    View

    @model AppName.Models.MyViewModel
     
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/index.js")" type="text/javascript"></script>
     
    <div id="result"></div>
     
    @using (Html.BeginForm())
    {
        @Html.EditorFor(x => x.Foo)
        @Html.ValidationMessageFor(x => x.Foo)
        <input type="submit" value="OK" />
    }

    Javascript

    <script>
        $(function () {
            $('form').submit(function () {
                if ($(this).valid()) {
                    $.ajax({
                        url: this.action,
                        type: this.method,
                        data: $(this).serialize(),
                        success: function (result) {
                            $('#result').html(result);
                        }
                    });
                }
                return false;
            });
        });
    </script>

      Modified On Apr-05-2018 07:05:05 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!