我想使用远程验证检查主类型是否已存在。
在我的情况下,远程验证方法没有解雇。任何人都可以帮助我吗?
[Key, Column(Order = 1)]
[StringLength(200)]
[Display(Name = "MasterType")]
[Remote("IsNameAvailable", "MasterSetUps", ErrorMessage = "Master type already exists ")]
public string MasterType { get; set; }
[AllowAnonymous]
public JsonResult IsNameAvailable(string MasterType)
{
bool result = true;
if (s_mode == "ADD")
{
return Json(!db.MasterSetUps.Any(a => a.MasterType == MasterType), JsonRequestBehavior.AllowGet);
}
else if (s_mode == "EDIT" & MasterType != s_Master_Type_name)
{
return Json(!db.MasterSetUps.Any(a => a.MasterType == MasterType), JsonRequestBehavior.AllowGet);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
<div class="form-group">
@Html.LabelFor(model => model.MasterType, htmlAttributes: new { @class = "control-label col-sm-2" })
<div class="col-sm-10">
@Html.DropDownList("MasterType", null, htmlAttributes: new { @class = "form-controls" })
@Html.ValidationMessageFor(model => model.MasterType, "", new { @class = "text-danger" })
</div>
</div>
public ActionResult Create()
{
s_mode = "ADD";
ViewBag.MasterType = new SelectList(db.Masters, "MasterType", "MasterType");
return View();
}
答案 0 :(得分:1)
您对DropDownList(...)
的使用意味着您没有为验证生成必要的data-val-*
属性。该方法使用您的ViewBag
属性进行绑定(而不是您的模型属性),并且它们没有与ViewBag
关联的验证属性。
将GET方法中的代码更改为
ViewBag.MasterTypeList = new SelectList (.....
和视图代码
@Html.DropDownListFor (m => m.MasterType, (SelectList)ViewBag.MasterTypeList, new { ... })
请注意,您绑定的属性名称不能与SelectList
相同。