leora
leora

Reputation: 196519

In asp.net-mvc, How can I insert a class name from my view model for a html.dropdownlistfor

I have the following code in my view:

<%= Html.DropDownListFor(r=>r.Id, Model.MyList, new { @class = "Dropdown hidden" })%>

but now I want to only assign the class "hidden" in certain cases so I want to pass that in from my ViewModel to either add the class or to leave it out.

To solve this, I created a property in my view model called HiddenConditional

  public string HiddenConditional
  {
      get
      {
          return IfCondition() ? "hidden" : string.empty;
      }
  }

but i can't figure out the right syntax to put that into the class attribute. I need something like:

<%= Html.DropDownListFor(r=>r.Id, Model.MyList, new { @class = "Dropdown <%=Model.HiddenConditional%>" })%>

Upvotes: 1

Views: 737

Answers (2)

John Washam
John Washam

Reputation: 4103

You may be tied to your solution of using HiddenConditional in your ViewModel, but I think it would be better to keep the class name in your View and simply use a boolean in your ViewModel. So it would look like this:

ViewModel

public bool MyListIsHidden { get; set; }

View

<%= Html.DropDownListFor(r=>r.Id, Model.MyList, new { @class = "Dropdown" + (Model.MyListIsHidden ? " hidden" : "") })%>

Upvotes: 1

hutchonoid
hutchonoid

Reputation: 33306

You need to do this:

<%= Html.DropDownListFor(r=>r.Id, Model.MyList, 
               new { @class = "Dropdown " + Model.HiddenConditional })%>

Upvotes: 1

Related Questions