Home > DeveloperSection > Forums > How to use Ajax.BeginForm in Asp.Net MVC?
jayprakash sharma
jayprakash sharma

Total Post:117

Points:821
Posted on    October-07-2014 11:17 PM

 ASP.NET MVC ASP.Net  ASP.NET MVC 
Ratings:


 1 Reply(s)
 840  View(s)
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.


Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    October-07-2014 11:22 PM

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>


Don't want to miss updates? Please click the below button!

Follow MindStick