Friday, July 19, 2013

How to Use Ajax.BeginForm in ASP.NET MVC

Below example demonstrate an example use of  Ajax.BeginForm. When the user click on the submit button the form will display "Thank You" on result DIV without causing a page reload.


public class MyViewModel
    public string Foo { get; set; }


public class HomeController : Controller
    public ActionResult Index()
        return View(new MyViewModel());

    public ActionResult Index(MyViewModel model)
        return Content("Thank You", "text/html");


@model AppName.Models.MyViewModel

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<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>

<div id="result"></div>

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <input type="submit" value="OK" />

No comments:
Write comments
Recommended Posts × +