14

This works:

<li @{if (Model.Mode == "map") {<text> class="bselected"</text>}}>@Html.ActionLink("Map & Directions", MVC.Biz.Show(Model.SingleBiz.BizName, "map", string.Empty))</li>

But it's ugly... Is there a better, cleaner way to do this? in this code, I'm checking if some view data is null or empty, if so add a class.

Or is there another technique to accomplish accomplish this better?

Chaddeus
  • 13,134
  • 29
  • 104
  • 162

5 Answers5

15

I posted some Html Extension methods yesterday that handle this kind of thing:

How to concisely create optional HTML attributes with razor view engine?

Using this approach would give you the following Razor syntax:

<li @Html.Css("selected", Model.Mode == "map" )>STUFF</li>

NOTE: you can chain attributes together to build up attribute values based upon multiple conditions. For example:

<li @Html.Css("selected", true).Add("winner", false).Add("last", true)>STUFF</li>

would output:

<li class="selected last">STUFF</li>

Also, if the resultant attribute value is empty the attribute will collapse to keep your html tidy.

Community
  • 1
  • 1
Lee Gunn
  • 8,417
  • 4
  • 38
  • 33
12

Or you could do something like this:

@{
    var cssClass = (Model.Mode == "map") ? "selected" : "";
}

<li class="@cssClass">@Html.ActionLink("Map & Directions", MVC.Biz.Show(Model.SingleBiz.BizName, "map", string.Empty))</li>
Simon Bartlett
  • 2,010
  • 14
  • 15
3

How about using a ternary operator to evalate an expression as follows:

<li @(Model.Mode == "map" ? "class='bselected' : "")>@Html.ActionLink("Map & Directions", MVC.Biz.Show(Model.SingleBiz.BizName, "map", string.Empty))</li> 
James H
  • 2,401
  • 3
  • 22
  • 20
2

Using a method in the @functions section:

@functions{
   public HtmlString Li(bool selected, IHtmlString template) {
      var result = string.Format("<li{0}>{1}</li>",
         selected ? " class='selected'" : "")),
         template);
      return new HtmlString(result);
   }
}

@* ... *@

@Li(Model.Mode == "map", Html.ActionLink("Map & Directions", MVC.Biz.Show(Model.SingleBiz.BizName, "map", string.Empty)))
GvS
  • 52,015
  • 16
  • 101
  • 139
0

I would probably say you could just add the class to your model

<li class="@Model.Selected">@Html.ActionLink("Map & Directions", MVC.Biz.Show(Model.SingleBiz.BizName, "map", string.Empty))</li>

That would clean it up...

Removed second example as I realized it won't work

Buildstarted
  • 26,529
  • 10
  • 84
  • 95
  • I like where you're going with this, but I would like to avoid having empty class="" in my output in the event it is not the selected item. – Chaddeus Nov 16 '10 at 22:41
  • You can use either example provided by Simon or myself to do it...You just supply the Model with your full class definition then or you do what Simon did with the full class definition – Buildstarted Nov 16 '10 at 22:47