0

I have a DropDownList and a TextArea in a Razor View. I want the TextArea to be visible only if specific value in the drop down has been selected. what solution is there to do that? Here is what I have tried so far but it is not quite right because it assumes the value of Security type is set.

<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> 
1
  • 1
    You need javascript/jquery if you want to respond to client side events. Commented Jul 25, 2016 at 3:51

1 Answer 1

1

Use jQuery when handling visibility of view element(s) on client-side event, with show or hide method. Here is an example:

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

If you prefer using vanilla 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>

Those scripts above assume id attribute of DropDownListFor and TextAreaFor are exactly same as the model binding name, depending on your needs.

AFAIK, if statement inside Razor works when a view performing callback or postback, thus only changes visibility after an ajax function or a form submit.

Any suggestions and improvements welcome.

References:

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.