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 f
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
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
}
and here's a better (in my perspective) example:
View:
@model AppName.Models.MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
}
index.js
:
$(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;
});
});
which can be further enhanced with the jQuery form plugin.