根据 DropDownListFor 显示/隐藏 div

0 javascript c# asp.net-mvc razor

div我需要帮助根据 DropDownListFor 中选定的值更改 2 个元素的可见性。

假设 dropDown 中有值“One”、“Two”和“Three”。

  • 我想显示div id="time"何时选择“一”或“二”的值并隐藏div id="fromTo"
  • 当选择值“三”时,我想显示div id="fromTo"和隐藏div id="time"

这是我目前拥有的代码:

<div class="form-group">
        @Html.LabelFor(model => model.I_Uloha, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.UlohaString, (SelectList)ViewBag.Tasks, new { @class = "form-control"})
            @Html.ValidationMessageFor(model => model.I_Uloha, "", new { @class = "text-danger" })
        </div>
</div>


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

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

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

Tet*_*oto 5

您需要使用 jQueryshow()hide()方法来更改div视图页面中元素的可见性,具体取决于下拉列表值,如下所示:

<script type="text/javascript">
$(document).ready(function () {
    $('#UlohaString').change(function () {
        var ddlValue = $(this).val();

        if (ddlValue == "One" || ddlValue == "Two")
        {
            // show time div, hide fromTo div
            $('#time').show();
            $('#fromTo').hide();
        }
        else if (ddlValue == "Three")
        {
            // show fromTo div, hide time div
            $('#fromTo').show();
            $('#time').hide();
        }
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

请注意,如果此处不起作用,则var ddlValue = $(this).find(':selected').text()可以使用。$(this).val()

参考:

如何使用 dropdownlist 更改事件在 asp.net mvc 5 中隐藏和显示 div