san*_*oIT 21 asp.net-mvc asp.net-ajax asp.net-mvc-3
我很抱歉,如果已经提出这个问题,但我一直在寻找,但我找到的只是相当旧的帖子(mvc1,mvc2).我有一个表格,我想通过Ajax提交.
这看起来会起作用,但不包括服务器端验证.
1)我不确定是否应该使用AjaxHelper.BeginForm
或使用原始jquery调用($.ajax)
?这里推荐的方法是什么?
2)如何处理客户端和服务器端验证?我希望mvc框架提供一个内置的机制来处理这个?有一些验证我只做服务器端.会不会ValidationSummary
在这里使用?
我使用asp.net mvc3/razor与unobtrussive javascript验证.
谢谢!
编辑:(按照Bobby B的要求). 这是在用户想知道如何使用AjaxHelper之后几个月提出问题
这是我使用的javascript代码:
<script type="text/javascript">
function ajaxValidate() {
return $('form').validate().form();
}
function getGbPostSuccess(ajaxContext){
// .... it is not necessary to do anything here.
}
function showFaliure(ajaxContext){
// handle failure
}
Run Code Online (Sandbox Code Playgroud)
HTML片段:
@using (Ajax.BeginForm("Index", "Home", new AjaxOptions
{
UpdateTargetId = "form1",
InsertionMode = InsertionMode.Replace,
OnBegin = "ajaxValidate",
OnSuccess = "getGbPostSuccess",
OnFailure = "showFaliure"
}))
{
Run Code Online (Sandbox Code Playgroud)
为此,我一直在使用malsup的jQuery表单插件.老实说,我对AjaxHelper并不熟悉,但确实看起来它会做你正在寻找的东西.就客户端和服务器端验证而言,只要您使用模型绑定和System.DataAnnotations命名空间中的属性,这一切都应该自动完成.
public class MyModel
{
[Required(ErrorMessage = "Please enter your name")]
public String Name { get; set; }
[Required(ErrorMessage = "Please enter your email")]
public String Email { get; set; }
[Required(ErrorMessage = "Please enter a rating")]
[Range(1, 5, ErrorMessage = "The rating must be between 1 and 5")]
public Int32 Rating { get; set; }
}
[HttpPost]
public ActionResult Index(MyModel myModel)
{
if(ModelState.IsValid)
{
// good to go, put it in the DB or whatever you need to do
}
else
{
return View(model); // return the user back to the page, ModelState errors can be viewed using Html.ValidationSummary() or individual Html.ValidationMessageFor() calls
}
}
Run Code Online (Sandbox Code Playgroud)
如果您正在进行自己的自定义服务器端验证,则可以通过创建实现ValidationAttribute的属性来创建自己的自定义验证属性,或者通过调用ModelState.Errors.Add()(或其周围的某些内容来添加验证错误)我没有参考方便)
对于客户端,MVC将根据模型上的DataAnnotations属性为您生成客户端验证.