开发者

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

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 acc开发者_运维百科omplish accomplish this better?


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>


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> 


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)))


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜