asp.net-mvc 如何使用剃刀视图引擎简洁地创建可选的 HTML 属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3800473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to concisely create optional HTML attributes with razor view engine?
提问by JarrettV
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.
我正在寻找一种用更少的代码行(可能是 5 行)编写以下代码的方法。我想我可以做与所选课程相同的事情,但这种剃刀语法看起来并不漂亮。
<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>
回答by JarrettV
Fixed in ASP.NET MVC 4
已在 ASP.NET MVC 4 中修复
see 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 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:
现在 Razor 能够自动处理该问题,因此您只需写出属性即可。如果为 null,则不写入该属性:
<div class="@myClass">Content</div>
So if @myClass is null, the output is just this:
所以如果@myClass 为空,输出就是这样:
<div>Content</div>
回答by Lee Gunn
I've come up with a chainable HtmlAttribute class and some Html Extension methods to allow the Razor syntax below:
我想出了一个可链接的 HtmlAttribute 类和一些 Html 扩展方法来允许下面的 Razor 语法:
<ul>
@foreach (var mi in items) {
<li @Html.Css("selected", mi.Selected)>
<a href="@mi.Href" @Html.Attr("title", mi.Title)>@mi.Text</a>
</li>
}
</ul>
Here is the HtmlAttribute class:
这是 HtmlAttribute 类:
public class HtmlAttribute : IHtmlString
{
private string _InternalValue = String.Empty;
private string _Seperator;
public string Name { get; set; }
public string Value { get; set; }
public bool Condition { get; set; }
public HtmlAttribute(string name)
: this(name, null)
{
}
public HtmlAttribute( string name, string seperator )
{
Name = name;
_Seperator = seperator ?? " ";
}
public HtmlAttribute Add(string value)
{
return Add(value, true);
}
public HtmlAttribute Add(string value, bool condition)
{
if (!String.IsNullOrWhiteSpace(value) && condition)
_InternalValue += value + _Seperator;
return this;
}
public string ToHtmlString()
{
if (!String.IsNullOrWhiteSpace(_InternalValue))
_InternalValue = String.Format("{0}=\"{1}\"", Name, _InternalValue.Substring(0, _InternalValue.Length - _Seperator.Length));
return _InternalValue;
}
}
Extra info: The "seperator" is used to chain together multiple values for an attribute. This can be useful for multiple css class names (use a space) or perhaps use String.Empty to build an value dependant on multiple conditions (by using the .Add() method)
额外信息:“分隔符”用于将一个属性的多个值链接在一起。这对于多个 css 类名(使用空格)或使用 String.Empty 来构建依赖于多个条件的值(通过使用 .Add() 方法)很有用
And here are the Html Extension helper methods:
以下是 Html Extension 辅助方法:
public static class Extensions
{
public static HtmlAttribute Css(this HtmlHelper html, string value)
{
return Css(html, value, true);
}
public static HtmlAttribute Css(this HtmlHelper html, string value, bool condition)
{
return Css(html, null, value, condition);
}
public static HtmlAttribute Css(this HtmlHelper html, string seperator, string value, bool condition)
{
return new HtmlAttribute("class", seperator).Add(value, condition);
}
public static HtmlAttribute Attr(this HtmlHelper html, string name, string value)
{
return Attr(html, name, value, true);
}
public static HtmlAttribute Attr(this HtmlHelper html, string name, string value, bool condition)
{
return Attr(html, name, null, value, condition);
}
public static HtmlAttribute Attr(this HtmlHelper html, string name, string seperator, string value, bool condition)
{
return new HtmlAttribute(name, seperator).Add(value, condition);
}
}
Let me know if they are of use.
让我知道它们是否有用。
Thanks,
谢谢,
Lee
李
回答by Buildstarted
<ul>
@foreach (var mi in Model.MenuItems) {
<li@(mi.Selected?" class=\"selected\"":null)>
<a href="@mi.Href" @{if(!string.IsNullOrEmpty(mi.Title)) { <text>title="@mi.Title"</text>} }>@mi.Text</a>
</li>
}
</ul>
I haven't tested it but it parses correctly.
我还没有测试它,但它解析正确。
回答by Darin Dimitrov
That would be a good candidate for custom HTML helper:
这将是自定义 HTML 助手的一个很好的候选者:
public static class HtmlExtensions
{
public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper, MenuItem mi)
{
var li = new TagBuilder("li");
if (mi.Selected)
{
li.AddCssClass("selected");
}
var a = new TagBuilder("a");
a.MergeAttribute("href", mi.Href);
if (!string.IsNullOrEmpty(mi.Title))
{
a.MergeAttribute("title", mi.Title);
}
a.SetInnerText(mi.Text);
return MvcHtmlString.Create(li.ToString());
}
}
and in your view:
在您看来:
<ul>
@foreach (var mi in Model.MenuItems) {
@Html.MenuItem(mi)
}
</ul>
or using DisplayTemplates you don't even need to write a loop:
或者使用 DisplayTemplates 您甚至不需要编写循环:
<ul>
@Html.DisplayFor(x => x.MenuItems)
</ul>
回答by Konstantin Tarkus
<ul>
@foreach (var mi in Model.MenuItems) {
<li@(Html.Raw((mi.Selected ? " class=\"selected\"" : null))>
<a href="@mi.Href">@mi.Text</a>
</li>
}
</ul>
回答by Darius Kucinskas
classattribute would not be rendered by Razor if value is null
class如果 value 是,则 Razor 不会呈现属性 null
<a href="#nolink" class="@(categoryId == null ? "submenu-active": null)">All</a>
回答by Robert Massa
For the case of multiple classes I use this simple extension method:
对于多个类的情况,我使用这个简单的扩展方法:
public static MvcHtmlString If(this string text, bool condition) {
return new MvcHtmlString(condition ? text : string.Empty);
}
And in the view:
在视图中:
<div class="menuitem @("active".If(Model.Active))">
回答by Christopher Davies
It's really pretty simple and clean:
这真的非常简单和干净:
<p @(cssClass != null) ? { class="@cssClass" }> Stuff and whatnot... </p>

