【问题标题】:Foolproof required value based on Dropdown value [duplicate]基于下拉值的万无一失的要求值[重复]
【发布时间】:2016-03-20 06:38:22
【问题描述】:

我发现了 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”类型。

编辑:

我包含的库是:

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

【问题讨论】:

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


    【解决方案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&lt;SelectListItem&gt; LeadSourceList { get; set;}的视图模型

    【讨论】:

    • 如果模型属性和ViewBag动态属性名称相同,框架就没有问题。由于模型属性用于创建具有模型绑定名称的输入控件。你给的把collection参数改成SelectList的答案也是我给的。但是,您有一个语法错误@Html.DropDownList("LeadSource_Id", IEnumerable&lt;SelectListItem&gt;ViewBag.LeadSourceList , @class = "form-control" })。如果您注意到您错过了@class 之前的{ 用于html 属性声明。我很抱歉,如果它被视为报复投票。我又投票了。
    • @user1672994 感谢您指出错字(现已修复)。将绑定到的属性和 ViewBag 属性同名存在问题,并且在 SO 上有许多与此相关的问题/答案(例如 this one)。但问题不在于名称,或者第二个参数是否为SelectList,而是ViewBag.LeadSource_Id 的值为null,这意味着DropDownListFor() 方法期望模型属性为@987654335 @(不是)
    猜你喜欢
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    相关资源
    最近更新 更多