.Net MVC Validation之Remote 模式
CusBusInfo.cs
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "業務夥伴程式碼")]
[Required(ErrorMessage = "業務夥伴程式碼不能為空!")]
[Index("IX_CusBusInfor_Key", IsUnique = true, Order = 1)]
[MaxLength(20)]
[System.Web.Mvc.Remote("GetIsUse", "CusBusInfos", AdditionalFields = "Id", HttpMethod = "post", ErrorMessage = "業務夥伴程式碼已存在")]
public string EnterpriseId { get; set; }
HttpMethod :xhr傳送請求 模式:post,get
AdditionalFields:需要額外拋到後臺的欄位,沒有的話,預設就欄位本身
HTML頁面
需要引用這2個JS檔案(或者在建試圖的時候勾選:引用指令碼庫)
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<div class="form-group col-lg-4 col-md-4 col-sm-4">
@Html.LabelFor(model => model.EnterpriseId, "業務夥伴程式碼", htmlAttributes: new { @class = "control-label " })
@Html.EditorFor(model => model.EnterpriseId, new { htmlAttributes = new { @class = "easyui-textbox1", data_options = "required:true ,validType:'length[0,20]'", tabindex = Num++, style = "width:100%" } })
@Html.ValidationMessageFor(model => model.EnterpriseId, "", new { @class = "text-danger" })
</div>
Controller
public ActionResult GetIsUse(int Id,string EnterpriseId)
{
var IsUse = _cusBusInfoService.Queryable().Any(x => x.EnterpriseId == EnterpriseId && x.Id !=Id);
return Json(!IsUse);
//get需要增加JsonRequestBehavior.AllowGet,不然會報安全錯誤
}
設定可以說是非常簡單,大部分工作都由微軟 幫我們做了,我們只需要關心業務邏輯