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?
Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML.
Inline Code refers to the code that is written inside an ASP.NET Web Page that has an extension of . aspx. It allows the code to be written along with the HTML source code using a <Script> tag.
Razor code blocksUse this approach to render HTML that isn't surrounded by an HTML tag. Without an HTML or Razor tag, a Razor runtime error occurs. The <text> tag is useful to control whitespace when rendering content: Only the content between the <text> tag is rendered.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With