MVC驗證09-使用MVC的Ajax.BeginForm方法實現非同步驗證

Darren Ji發表於2014-03-05

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"});
            }
        }
    }
}
 

讓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);
            }
        }
 
    }
}
 

無論驗證成功或失敗,都返回強型別部分檢視。

 

  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>
 

  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>
}
 

  Home/Success.cshmtl檢視

@model XHelent.Models.Registration
 
<h2>恭喜,註冊成功了!</h2>
<p>註冊號為:@Model.RegisrationUniqueId</p>
 

沒有填寫效果:

影象 1

 

年齡小於18效果:

影象 2

 

輸入正確效果:

影象 3


==總結

使用Ajax.BeginForm()雖然可以實現非同步提交併驗證,但,如果放到後臺管理系統的背景下,返回部分檢視可能不是很方便。

相關文章