基于下拉值的万无一失的必需值

时间:2015-12-14 17:14:16

标签: c# asp.net-mvc data-annotations foolproof-validation

我发现了一个看起来非常好的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; }

我在Controller中创建Dropdown的方式:

 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&lt; SelectListItem&gt;'类型。

编辑:

我包含的库是:

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

1 个答案:

答案 0 :(得分: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;}

的视图模型