【问题标题】:Remote Validate for DropDownList, MVC3, not firing in my caseDropDownList,MVC3的远程验证,在我的情况下没有触发
【发布时间】:2012-07-22 09:02:31
【问题描述】:

我正在使用 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>
}

【问题讨论】:

    标签: asp.net asp.net-mvc-3 validation


    【解决方案1】:

    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-04-09
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      相关资源
      最近更新 更多