【问题标题】:access MVC dropdown selected value in the same view在同一视图中访问 MVC 下拉选择值
【发布时间】:2016-07-25 03:47:18
【问题描述】:

我在 Razor 视图中有一个 DropDownList 和一个 TextArea。我希望只有在选择了下拉列表中的特定值时才能看到 TextArea。有什么解决方案可以做到这一点?到目前为止,这是我尝试过的,但它并不完全正确,因为它假定设置了 Security 类型的值。

<tr>
    <td style="width: 200px; height: 30px">
        @Html.LabelFor(model => model.SecurityTypeId)
    </td>
    <td style="width: 400px; height: 30px">
        @Html.DropDownListFor(model => model.SecurityTypeId, Model.SecurityTypes, dropdownHtmlAttrs)
    </td>
    <td>&nbsp;</td>
</tr>
<tr>
    @if (Model.SecurityTypeId == (int)(SecurityType.Other))
    {
        <td style="width: 200px; height: 30px">
            @Html.LabelFor(model => model.Details)
        </td>
        <td style="width: 400px; height: 30px">
            @Html.TextAreaFor(model => model.Details, new { Style = "width:240px" })
        </td>
        <td>&nbsp;</td>
    }
</tr> 

【问题讨论】:

  • 如果你想响应客户端事件,你需要javascript/jquery。

标签: asp.net-mvc razor


【解决方案1】:

在客户端事件上处理视图元素的可见性时使用 jQuery,使用 showhide 方法。这是一个例子:

<script type="text/javascript">
$(document).ready(function () {
     $('#SecurityTypeId').change(function () {
          var value = $(this).val(); // get selected value
          if (value == "set") { // this condition may adjusted to certain preset value
              $('#Details').show(); // show text area
          }
          else {
              $('#Details').hide(); // hide text area
          }
     });
});
</script>

如果你更喜欢使用原生 JS:

<script type="text/javascript">
    var ddlvalue = document.getElementById("SecurityTypeId").value;
    if (ddlvalue == "set") {
        document.getElementById("Details")).style.visibility = "visible";
    }
    else {
        document.getElementById("Details")).style.visibility = "hidden";
    }
</script>

以上脚本假定DropDownListForTextAreaFor 的id 属性与模型绑定名称完全相同,具体取决于您的需要。

AFAIK,当视图执行回调或回发时,Razor 中的 if 语句有效,因此仅在 ajax 函数或表单提交后更改可见性。

欢迎提出任何建议和改进。

参考资料:

how to hide and show text box according to select value using jquery

Show/hide control based on dropdown selection mvc 4 razor c#

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多