-1

我发现了 Foolproof 库,它看起来非常好,但我在让它工作时遇到了问题。

仅当下拉列表的选定值 = 7 时,我才想创建一个必填字段。

简单模型:

[RequiredIf("LeadSource_Id","7", ErrorMessage = "Campo obrigatório")]
public string SourceDescription { get; set; }

[Display(Name = "Origem")]
public virtual int LeadSource_Id { get; set; }

我在控制器中创建下拉菜单的方式:

 ViewBag.LeadSource_Id = new SelectList(db.LeadSources.ToList(), "Id", "Name");

风景:

<div class="form-group">
    @Html.LabelFor(model => model.LeadSource_Id, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("LeadSource_Id", null, htmlAttributes: new { @class = "form-control ld-lead-source" })
        @Html.ValidationMessageFor(model => model.LeadSource_Id, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group collapse">
    @Html.LabelFor(model => model.SourceDescription, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.SourceDescription, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.SourceDescription, "", new { @class = "text-danger" })
    </div>
</div>

当我在选择值 7 时尝试查看验证是否有效时,我收到错误消息:

具有键“LeadSource_Id”的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable<SelectListItem>”类型。

编辑:

我包括的库是:

<script src="~/Scripts/jquery/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery/jquery.validate.globalize.min.js"></script>
<script src="~/Scripts/mvcfoolproof.unobtrusive.min.js"></script>
4

1 回答 1

1

发生错误是因为 的ViewBag.LeadSource_Id值为null。由于您已在 GET 方法中设置了它的值,因此当您在 POST 方法中返回视图(您已省略)但未重新分配该值时,可能会发生此错误。此外,您不能为该ViewBag属性指定与您的模型属性相同的名称。

将您的控制器代码更改为(比如说)

ViewBag.LeadSourceList = new SelectList(db.LeadSources.ToList(), "Id", "Name");

并确保此代码出现在 GET 方法和 POST 方法中是您返回视图,并将视图修改为

@Html.DropDownList("LeadSource_Id", IEnumerable<SelectListItem>ViewBag.LeadSourceList , { @class = "form-control" })

但是,推荐的方法是使用包含属性的视图模型public IEnumerable<SelectListItem> LeadSourceList { get; set;}

于 2015-12-14T20:55:54.277 回答