【问题标题】:mvc 5 if dropdownlist selected option than required different model propertymvc 5 如果下拉列表选择的选项比所需的不同模型属性
【发布时间】:2019-10-27 11:12:44
【问题描述】:

我有一个包含多个控件的视图。我想要的是当我的下拉列表中的 1 个选择了特定值时,如果选择了该值,那么我需要不同的控件属性。通常通常不需要此属性。如果在我的下拉列表中选择了这个值,我只希望它是一个要求。在我的模型中,我通常可以只将 required 添加到属性中,但我该怎么做,就像我上面问的那样。如果‘usuage=value1’则需要数量 + 单位。有没有办法在控制器动作中做到这一点?或者只能通过 JavaScript 实现。这是我针对这种情况的代码。

<div class="form-group row">
<div class="col-md-4 col-lg-4">
@Html.LabelFor(x => x.Usage,
htmlAttributes: new { @class = "control-label" })
</div>
<div class="col-md-8 col-lg-8">
@Html.DropDownListFor(x => x.Usage,
(IEnumerable<SelectListItem>) ViewBag.UsageDDL,
"", new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Usage, "",
new { @class = "text-danger" })
</div>
</div> <div class="form-group row">
<div class="col-md-4 col-lg-4">
@Html.LabelFor(x => x.Quantity,
htmlAttributes: new { @class = "control-label" })
</div>
<div class="col-md-8 col-lg-8">
@Html.EditorFor(x => x.Quantity, new { htmlAttributes =
new { @class = "form-control", @type = "number" }})
@Html.ValidationMessageFor(x => x.Quantity, "",
new { @class = "text-danger" })
</div>
</div>

<div class="form-group row">
<div class="col-md-4 col-lg-4">
@Html.LabelFor(x => x.Units,
htmlAttributes: new { @class = "control-label" })
</div>
<div class="col-md-8 col-lg-8">
@Html.DropDownListFor(x => x.Units,
(IEnumerable<SelectListItem>) ViewBag.UnitsDDL,
"", new { @class="form-control" })
@Html.ValidationMessageFor(x => x.Units, "",
new { @class = "text-danger" })
</div>
</div>

【问题讨论】:

  • 模型不能动态改变,所以你可能想创建自己的验证方法。 (客户端和服务器端。)

标签: javascript c# mvvm asp.net-mvc-5


【解决方案1】:

看来您肯定需要使用客户端代码(显然是 javascript),尽管您可以完全在服务器端执行此操作,但它会在最浅的地方越过流。

你可以使用这样的东西:

@Html.DropDownList("Usage", new SelectListItem[] 
{ 
 new SelectListItem() { Text = "one", Value = "0" }, 
 new SelectListItem() { Text = "two", Value = "1" }},
 new { @onchange="handler(this.value)" 
});

<script>
function handler(val){
    //option1 : refresh current page based on Usage and make Quantity and Unit desabled in your Razor Page.
    window.location.href = "/Controller/CurrentAction?Usage=" + val;
    // option2 : make Quantity and Unit desabled by javascrip code without refresh page.
    var form = document.forms[0];
    form.querySelector('input[name="Quantity"]').disabled = true;
    form.querySelector('input[name="Unit"]').disabled = true;
}
</script>

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-23
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多