首页 > 代码库 > MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证

MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证

原文:MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证

MVC中,关于往后台提交的方法有:
1、Html.BeginForm():同步
2、Ajax.BeginForm():异步
3、js或jQuery提交后台

本文体验Ajax.BeginForm()方法。

  View model

using System;
using System.ComponentModel.DataAnnotations;
 
namespace XHelent.Models
{
    public class Registration : IValidatableObject
    {
        
        public string RegisrationUniqueId { get; set; }
 
        [Required]
        [Display(Name = "姓名")]
        public string Name { get; set; }
 
        [Required]
        [Display(Name = "年龄")]
        public int Age { get; set; }
 
        public System.Collections.Generic.IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (Age < 18)
            {
                yield return new ValidationResult("年龄至少18岁以上", new String[]{"Age"});
            }
        }
    }
}
 
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>

让model实现了IValidatableObject,在model层自定义验证逻辑和错误信息。

 

  HomeController

using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using XHelent.Models;
 
namespace XHelent.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new Registration());
        }
 
        [HttpPost]
        public PartialViewResult Index(Registration model)
        {
            if (ModelState.IsValid)
            {
                RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
                byte[] registrationBytes = new byte[16];
                csp.GetBytes(registrationBytes);
                model.RegisrationUniqueId = Convert.ToBase64String(registrationBytes);
                return PartialView("Success", model);
            }
            else
            {
                return PartialView("FormContent", model);
            }
        }
 
    }
}
 
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>

无论验证成功或失败,都返回强类型部分视图。

 

  Home/Index.cshtml视图

@model XHelent.Models.Registration
 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>当前时间:@DateTime.Now.ToShortDateString()</h2>
 
<div id="formContent">
    @{Html.RenderPartial("FormContent");}
</div>
 
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>

  Home/FormContent.cshtml部分视图

@model XHelent.Models.Registration
 
@{
    AjaxOptions options = new AjaxOptions
    {
        HttpMethod = "Post",
        UpdateTargetId = "formContent" //可忽略
    };
}
 
<style type="text/css">
    .field-validation-error {
        color: red;
    }
</style>
 
@using (Ajax.BeginForm(options))
{
    <fieldset>
        <legend>登记</legend>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        
        <div class="editor-label">
            @Html.LabelFor(model => model.Age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)
        </div>
        
        <div>
            <input type="submit" value="登记"/>
        </div>
    </fieldset>
}
 
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>

  Home/Success.cshmtl视图

@model XHelent.Models.Registration
 
<h2>恭喜,注册成功了!</h2>
<p>注册号为:@Model.RegisrationUniqueId</p>
 
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>
没有填写效果:

图像 1

 

年龄小于18效果:

图像 2

 

输入正确效果:

图像 3


==总结

使用Ajax.BeginForm()虽然可以实现异步提交并验证,但,如果放到后台管理系统的背景下,返回部分视图可能不是很方便。