繁体   English   中英

mvc 5如果dropdownlist选择的选项比所需的其他模型属性更多

[英]mvc 5 if dropdownlist selected option than required different model property

我有一个带有多个控件的视图。 我想要的是当我的下拉列表中的一个具有选定的特定值时(如果选择了该值),那么我需要一个不同的控件属性。 通常通常不需要此属性。 如果在我的下拉列表中选择了此值,我只希望它成为要求。 在我的模型中,我通常只能向属性添加必填项,但是如我上面所述,我该如何做。 如果'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),尽管您可以完全在服务器端执行此操作,但是它会跨过最浅的流。

您可以使用以下方法:

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

我希望这能帮到您

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM