如何简明创建的Razor视图引擎可选HTML属性? [英] How to concisely create optional HTML attributes with razor view engine?

查看:94
本文介绍了如何简明创建的Razor视图引擎可选HTML属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方式来编写如下code。与code(也许5)少行。我想我可以做同样的事情作为选定类,但这种剃须刀的语法是不是找pretty。

 < UL>
@foreach(在Model.MenuItems VAR英里){
  <李@(?mi.Selected级= \\选择\\:NULL)>
  @if(string.IsNullOrEmpty(mi.Title)){
    &所述; A HREF =@ mi.Href> @ mi.Text&下; / A>
  }其他{
    < A HREF =@ mi.Href称号=@ mi.Title> @ mi.Text< / A>
  }
  < /李>
}
< / UL>


解决方案

在ASP.NET MVC 4固定

看<一个href=\"http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx\">http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx

Conditional属性渲染

如果您有可能为空,在过去的你需要做一个空检查,以避免写出一个空的属性,像这样的属性:

 &LT; D​​IV @ {如果(MyClass的!= NULL){&LT;文字和GT;类=@ MyClass的&LT; /文字和GT; }}&gt;内容&LT; / DIV&GT;

现在剃刀能够自动处理的,所以你可以只写出来的属性。如果它为空,则该属性不会被写入:

 &LT; D​​IV CLASS =@ MyClass的&gt;内容&LT; / DIV&GT;

所以,如果@myClass为空,则输出仅仅是这样的:

 &LT; D​​IV&gt;内容&LT; / DIV&GT;

I'm looking for a way to write the following code with less lines of code (maybe 5). I suppose I could do the same thing as the selected class but this razor syntax isn't looking pretty.

<ul>
@foreach (var mi in Model.MenuItems) {
  <li@(mi.Selected?" class=\"selected\"":null)>
  @if (string.IsNullOrEmpty(mi.Title)) {
    <a href="@mi.Href">@mi.Text</a>
  } else {
    <a href="@mi.Href" title="@mi.Title">@mi.Text</a>
  }
  </li>
}
</ul>

解决方案

Fixed in ASP.NET MVC 4

see http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx

Conditional attribute rendering

If you have an attribute that might be null, in the past you've needed to do a null check to avoid writing out an empty attribute, like this:

<div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>

Now Razor is able to handle that automatically, so you can just write out the attribute. If it's null, the attribute isn't written:

<div class="@myClass">Content</div>

So if @myClass is null, the output is just this:

<div>Content</div>

这篇关于如何简明创建的Razor视图引擎可选HTML属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆