0

我正在使用 ASP.NET MVC3 和 EF 4.1 我的模型中有两个 DropDownList,它是必需的,也不重复。我想要远程验证功能:ValidateDuplicateInsert 在用户提交数据时触发。但我无法触发 ValidateDuplicateInsert 函数。我哪里错了?

我的模特

    [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; }

我的 CMAndOrg 控制器中的 ValidateDuplicateInsert 函数

    [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>
}
4

1 回答 1

0

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"))

再次感谢亨利赫

原文链接 http://www.codeproject.com/Articles/249452/ASP-NET-MVC3-Validation-Basic?msg=4330725#xx4330725xx

于 2012-08-09T07:16:04.867 回答