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

讓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()雖然可以實現異步提交並驗證,但,如果放到后台管理系統的背景下,返回部分視圖可能不是很方便。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM