標籤:style blog http color 使用 width
原文: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>
沒有填寫效果:
年齡小於18效果:
輸入正確效果:
==總結
使用Ajax.BeginForm()雖然可以實現非同步提交並驗證,但,如果放到後台管理系統的背景下,返回部分視圖可能不是很方便。