使用Ajax.BeginForm与ASP.NET MVC 3剃须刀 [英] Using Ajax.BeginForm with ASP.NET MVC 3 Razor
本文介绍了使用Ajax.BeginForm与ASP.NET MVC 3剃须刀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有使用的教程或code例如 Ajax.BeginForm
Asp.net MVC 3内不显眼的地方验证和Ajax存在?
Is there a tutorial or code example of using Ajax.BeginForm
within Asp.net MVC 3 where unobtrusive validation and Ajax exist?
这是MVC 3难以捉摸的话题,我似乎无法让我的形式才能正常工作。它会做一个Ajax提交,而忽略验证错误。
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.
推荐答案
例如:
型号:
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" />
}
和这里是一个更好的(在我的角度)例如:
and here's a better (in my perspective) example:
查看:
@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;
});
});
可与的jQuery插件的形式进一步增强。
这篇关于使用Ajax.BeginForm与ASP.NET MVC 3剃须刀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文