asp.net mvc 3 - ajax表单提交和验证

时间:2022-08-02 16:38:30

I am sorry if this has been asked already, but I have been looking for sometime but all I have found are rather old posts (mvc1, mvc2). I have a form which I would like to submit via Ajax.

我很抱歉,如果已经提出这个问题,但我一直在寻找,但我找到的只是相当旧的帖子(mvc1,mvc2)。我有一个表格,我想通过Ajax提交。

This looks like it would work but does not cover server side validation.

这看起来会起作用,但不包括服务器端验证。

1) I am unsure if I should use the AjaxHelper.BeginForm or use raw jquery calls ($.ajax)? What is the recommended approach here?

1)我不确定是否应该使用AjaxHelper.BeginForm或使用原始jquery调用($ .ajax)?这里推荐的方法是什么?

2) How do I handle client and server side validation? I am hoping the mvc framework provides a built in mechanism for dealing with this? There are some validations which I am only doing server side. Would using a ValidationSummary still work here?

2)如何处理客户端和服务器端验证?我希望mvc框架提供一个内置的机制来处理这个?有一些验证我只做服务器端。使用ValidationSummary仍然可以在这里工作吗?

I am using asp.net mvc3/razor with unobtrussive javascript validation.

我使用asp.net mvc3 / razor与unobtrussive javascript验证。

Thank you!

谢谢!

Edit: (as requested by Bobby B below). This was added months after asking the question as a user wanted to know how to use AjaxHelper

编辑:(按照Bobby B的要求)。这是在用户想知道如何使用AjaxHelper之后几个月提出问题后添加的

This is the javascript code I used:

这是我使用的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
}

HTML snippet:

HTML片段:

@using (Ajax.BeginForm("Index", "Home", new AjaxOptions
                        {
                            UpdateTargetId = "form1",
                            InsertionMode = InsertionMode.Replace,
                            OnBegin = "ajaxValidate",
                            OnSuccess = "getGbPostSuccess",
                            OnFailure = "showFaliure"
                        }))
{

2 个解决方案

#1


8  

I've been using malsup's jQuery form plugin for a while for this purpose. I'm honestly not familiar with AjaxHelper, but does look like it'll do what you're looking for. As far as doing both client and server side validation, that should all happen mostly automatically as long as you're using model binding and the attributes from the System.DataAnnotations namespace.

为此,我一直在使用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
   }
}

If you're doing your own custom server-side validation, you can either create your own custom validation attribute by creating an attribute that implements ValidationAttribute, or just add validation errors by calling ModelState.Errors.Add() (or something around there, I don't have a reference handy)

如果您正在进行自己的自定义服务器端验证,则可以通过创建实现ValidationAttribute的属性来创建自己的自定义验证属性,或者通过调用ModelState.Errors.Add()(或其周围的某些内容来添加验证错误)我没有参考方便)

For client side, MVC will generate clientside validation for you based on the DataAnnotations attributes on your model.

对于客户端,MVC将根据模型上的DataAnnotations属性为您生成客户端验证。

#2


1  

MVC.NET 3 already has this out of the box. Just make sure to have ClientValidationEnabled enabled in the web.config. Check this

MVC.NET 3已经开箱即用了。只需确保在web.config中启用ClientValidationEnabled。检查一下

#1


8  

I've been using malsup's jQuery form plugin for a while for this purpose. I'm honestly not familiar with AjaxHelper, but does look like it'll do what you're looking for. As far as doing both client and server side validation, that should all happen mostly automatically as long as you're using model binding and the attributes from the System.DataAnnotations namespace.

为此,我一直在使用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
   }
}

If you're doing your own custom server-side validation, you can either create your own custom validation attribute by creating an attribute that implements ValidationAttribute, or just add validation errors by calling ModelState.Errors.Add() (or something around there, I don't have a reference handy)

如果您正在进行自己的自定义服务器端验证,则可以通过创建实现ValidationAttribute的属性来创建自己的自定义验证属性,或者通过调用ModelState.Errors.Add()(或其周围的某些内容来添加验证错误)我没有参考方便)

For client side, MVC will generate clientside validation for you based on the DataAnnotations attributes on your model.

对于客户端,MVC将根据模型上的DataAnnotations属性为您生成客户端验证。

#2


1  

MVC.NET 3 already has this out of the box. Just make sure to have ClientValidationEnabled enabled in the web.config. Check this

MVC.NET 3已经开箱即用了。只需确保在web.config中启用ClientValidationEnabled。检查一下