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
<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" />
}
and here's a better (in my perspective) example:
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" />
}
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.
Prior to adding the Ajax.BeginForm. Add below scripts to your project in the order mentioned,
Only these two are enough for performing Ajax operation.