create时使用remote特性没有任何问题,
update时,问题就大了,验证唯一性时需要排除自身,如果使用这个特性将无法正确的验证.
改进思路:将自动生成的标签属性改为手写,,并在url上面加上验证参数;
去掉Model的Remote特性
标签生成代码:
1 @Html.TextBoxFor(r => r.Code, 2 new Dictionary<string, object>{ 3 {"data-val-remote","该编码已存在!"}, 4 {"class","form-control"},
5 {"data-val-remote-additionalfields","*.Code"}, 6 {"data-val-remote-type","post"}, 7 {" data-val-remote-url","/Test/CheckCode"+((Model==null)?"":"?self="+Model.Id.ToString())}})
验证代码:
public JsonResult CheckCode(string code, Guid? self = null) { code = code.ToUpper().Trim(); bool b; if (self == null) b = _b.IsExists<Test>(r => r.code == code); else b = _b.IsExists<Test>(r => r.code == code && r.Id != self); return Json(!b, JsonRequestBehavior.AllowGet); }