user2284341
user2284341

Reputation: 671

Html.DropDownListFor make visible/not visible

I'm using the html helper fo a drop down menu ( Html.DropDownFor(...) ) in an MVC 3 project.

On loading the page, I want this drop down menu not visible. It will become visible depending on a choice of another drop down menu on the same page. I've written some JQuery to handle this which makes use of show() and hide(). This works for textboxes and labels but what I need is the correct syntax for the helper itself. I've tried:

<%:Html.DropDownListFor(a => Model.VariableOptionId, new { style = "display: none;" })%>
<%:Html.DropDownListFor(a => Model.VariableOptionId, Visible = false })%>

What is the correct syntax?

Upvotes: 1

Views: 3197

Answers (2)

Yushell
Yushell

Reputation: 745

You could just add a class, for example .dropdown and use $('.dropdown').toggle(); to toggle visibility.

The MVC Helper syntax would be:

<%:Html.DropDownListFor(a => Model.VariableOptionId, new { @class = "dropdown" }) %>

A small code example would be:

HTML

<div class="toggle">Click me to toggle!</div>
<br>
<div>
    <select class="dropdown">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>
</div>

JS / Jquery

$(document).delegate('.toggle', 'click', function () {
    $('.dropdown').toggle();
});

Working example: http://jsfiddle.net/8AKww/

Edited example: http://jsfiddle.net/8AKww/1/

Upvotes: 1

Sagar Modi
Sagar Modi

Reputation: 768

 @model MvcApplication1.Models.ProductViewModel
    <script type="text/javascript"    src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>


      @using (Html.BeginForm())
       {    
        @Html.DropDownListFor(x => x.SelectedMainCatId, new    SelectList(Model.MainCategory,"Value","Text"), "Select Main..")
          @Html.DropDownListFor(x => x.SelectedSubCatId, new SelectList(Model.SubCategory, "Value", "Text"), "Select Sub..")    
        <button type="submit">Save</button>
       }
       <script type="text/javascript">
        $(function () {
            $("#SelectedMainCatId").change(function () {
                var val = $(this).val();
                if(val == 'anycondition')
                 {
                         $("#SubCategory").hide();
                 } 
                 else
                        $("#SubCategory").show();
            });
        });
    </script>

Upvotes: 0

Related Questions