asp.net mvc 3 - ajax form submit and validation

╄→гoц情女王★ 提交于 2019-11-30 03:39:24

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.

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)

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!