是否有Ajax.BeginForm在 Asp.net MVC 3 中使用不显眼的验证和 Ajax 的教程或代码示例?
Ajax.BeginForm
对于 MVC 3,这是一个难以捉摸的话题,我似乎无法让我的表单正常工作。它将执行 Ajax 提交,但忽略验证错误。
例子:
模型:
public class MyViewModel { [Required] public string Foo { get; set; } }
控制器:
public class HomeController : Controller { public ActionResult Index() { return View(new MyViewModel()); } [HttpPost] public ActionResult Index(MyViewModel model) { return Content("Thanks", "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" /> }
这是一个更好的(在我看来)示例:
@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:
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; }); });
可以通过jQuery 表单插件进一步增强。