Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to have inline code blocks using the ASP.NET Razor view engine?

Tags:

syntax

c#

razor

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?

like image 452
Chaddeus Avatar asked Nov 16 '10 15:11

Chaddeus


People also ask

What is razor view in asp net?

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.

What is inline code in asp net?

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.

What is Razor code blocks?

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.


2 Answers

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.

like image 80
Lee Gunn Avatar answered Oct 13 '22 13:10

Lee Gunn


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>
like image 37
Simon Bartlett Avatar answered Oct 13 '22 14:10

Simon Bartlett