远程验证DropDownList,MVC3,在我的情况下没有触发
问题描述:
我正在使用ASP.NET MVC3和EF 4.1 我有两个DropDownList在我的模型中,它是必需的,也没有重复。 而我想要远程验证功能:ValidateDuplicateInsert在用户提交数据时触发。但我无法获得ValidateDuplicateInsert函数触发。 我错在哪里?远程验证DropDownList,MVC3,在我的情况下没有触发
我的模型
[Key]
public int CMAndOrgID { get; set; }
[Display(Name = "CM")]
[Required(ErrorMessage = "CM is required.")]
[Remote("ValidateDuplicateInsert", "CMAndOrg", HttpMethod = "Post", AdditionalFields = "CMID, OrganizationID", ErrorMessage = "CM is assigned to this Organization.")]
public int? CMID { get; set; }
[Display(Name = "Organization")]
[Required(ErrorMessage = "Organization is required.")]
public int? OrganizationID { get; set; }
public virtual CM CM { get; set; }
public virtual Organization Organization { get; set; }
的ValidateDuplicateInsert功能在我CMAndOrg控制器
[HttpPost]
public ActionResult ValidateDuplicateInsert(string cmID, string orgID)
{
bool flagResult = true;
foreach (CMAndOrg item in db.CMAndOrgs)
{
if (item.CMID.ToString() == cmID && item.OrganizationID.ToString() == orgID)
{
flagResult = false;
break;
}
}
return Json(flagResult);
}
而且我查看
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>CMAndOrg</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CMID, "CM")
</div>
<div class="editor-field">
@Html.DropDownList("CMID", String.Empty)
@Html.ValidationMessageFor(model => model.CMID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.OrganizationID, "Organization")
</div>
<div class="editor-field">
@Html.DropDownList("OrganizationID", String.Empty)
@Html.ValidationMessageFor(model => model.OrganizationID)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
答
有相关的上下拉列表不引人注目的验证在MVC3的错误。请参考此http://aspnet.codeplex.com/workitem/7629[^]链接了解更多详细说明。
简单地说,您不能使用类的收集和分类字段的名称相同,所以只是改变按照你的观点一致的集合名称和更新
@Html.DropDownList("CategoryID", String.Empty)
与此
@Html.DropDownListFor(model => model.CategoryID, new SelectList((System.Collections.IEnumerable)ViewData["Categories"], "Value", "Text"))
再次感谢Henry He
原创链接 http://www.codeproject.com/Articles/249452/ASP-NET-MVC3-Validation-Basic?msg=4330725#xx4330725xx