asp.net-mvc ASP.NET MVC razor:HTML 中的条件属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9399531/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:45:52  来源:igfitidea点击:

ASP.NET MVC razor: conditional attribute in HTML

asp.net-mvcasp.net-mvc-3razor

提问by Mahesh

Code below doesn't seems clean. Any suggestion to improve the code?

下面的代码似乎不干净。有什么建议可以改进代码吗?

<li @if(ViewData["pagename"].ToString()=="Business details"){ <text>class="active" </text> } >
        <a  @if(ViewData["pagename"].ToString()=="Business details"){ <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
            href="@Url.Action("BusinessDetails", "Business")">Business Details</a>
    </li> 
    <li @if (ViewData["pagename"].ToString() == "Booking policies"){ <text>class="active"</text> }> 
        <a  @if (ViewData["pagename"].ToString() == "Booking policies")
               { <text>style="color: white; background-color: #08C; border: 1px solid #08C;" </text> }
            href="@Url.Action("BookingPolicies", "Business")">Booking policies</a> 
    </li> 

回答by jcreamer898

MVC has conditional attributes built in...

MVC 具有内置的条件属性...

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

If @myClass is null, it just won't use the attribute at all...

如果@myClass 为空,则它根本不会使用该属性...

I know that may not quite solve your current issue, but it is noteworthy!

我知道这可能不能完全解决您当前的问题,但值得注意的是!

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

回答by SLaks

<li class="@(ViewBag.pagename == "Business details" ? "active" : null)">  

You should replace the inline style="..."with a separate classname and use the same syntax there.

您应该用style="..."单独的类名替换内联并在那里使用相同的语法。

However, it would be cleaner to make a separate HTML helper extension method that takes a page and action name and generates the HTML generically.

但是,制作一个单独的 HTML 帮助程序扩展方法会更清晰,该方法接受页面和操作名称并生成一般的 HTML。

回答by defrost

I use a small helper method that will conditionally add an attribute if the value is non-empty, and, if defined, when a Boolean function expression evaluates to true:

我使用一个小的辅助方法,如果值不为空,并且如果定义,当布尔函数表达式计算为时,它将有条件地添加一个属性true

public static MvcHtmlString Attr(this HtmlHelper helper, string name, string value, Func<bool> condition = null)
{
    if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
    {
        return MvcHtmlString.Empty;
    }

    var render = condition != null ? condition() : true;

    return render ? 
        new MvcHtmlString(string.Format("{0}=\"{1}\"", name, HttpUtility.HtmlAttributeEncode(value))) : 
        MvcHtmlString.Empty;
}

Once defined, I can use this method in my Razor views:

定义后,我可以在 Razor 视图中使用此方法:

<li @(Html.Attr("class", "new", () => example.isNew))>
...
</li>

The above code will render <li class="new">...</li>if example.isNew == true, if not will omit the entire classattribute.

上面的代码将呈现<li class="new">...</li>if example.isNew == true, if not 将省略整个class属性。

回答by David Slavík

In MVC4

在MVC4中

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    @{
        string css = "myDiv";
    }
    <div class='@css'></div>
</body>
</html>

or

或者

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    @{
        string css = "class=myDiv";
    }
    <div @css></div>
</body>
</html>

More are here: http://evolpin.wordpress.com/2012/05/20/mvc-4-code-enhancements/

更多在这里:http: //evolpin.wordpress.com/2012/05/20/mvc-4-code-enhancements/

回答by Pavlo Neiman

Approach with TagWrap extension method. Code for your question would look like this:

使用 TagWrap 扩展方法的方法。您的问题的代码如下所示:

@using (Html.TagWrap("li", condition ? new { @class = "active" } : null))
{
    var anchorAttrs = new Dictionary<string, object> { { "href", Url.Action("BusinessDetails", "Business") } };
    if(condition)
    {
        anchorAttrs["style"] = "color: white; background-color: #08C; border: 1px solid #08C;";
    }
    using (Html.TagWrap("a", anchorAttrs))
    {
        <text>Business Details</text>
    }
}

TagWrap extension methods

TagWrap 扩展方法

using Microsoft.AspNetCore.Mvc.ViewFeatures;

使用 Microsoft.AspNetCore.Mvc.ViewFeatures;

public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, object data)
{
    return htmlHelper.TagWrap(tagName, HtmlHelper.AnonymousObjectToHtmlAttributes(data));
}

public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, IDictionary<string, object> data)
{
    var tag = new TagBuilder(tagName);
    tag.MergeAttributes(data);

    htmlHelper.ViewContext.Writer.Write(tag.RenderStartTag());

    return new DisposableAction(() =>
        htmlHelper.ViewContext.Writer.Write(tag.RenderEndTag()));
}

Helper class used for rendering closing tag on Dispose

用于在 Dispose 上呈现结束标记的助手类

public class DisposableAction : IDisposable
{
    private readonly Action DisposeAction;

    public DisposableAction(Action action)
    {
        DisposeAction = action;
    }

    public void Dispose()
    {
        DisposeAction();
    }
}

回答by spaark

Based on defrosts answer here an adaptation, taking an objectinstead of a string:

基于除霜回答这里的一个适应,采用一个object而不是一个string

    public static MvcHtmlString ConditionalAttr(this HtmlHelper helper, string attributeName, object value, Func<bool> condition)
    {
        if (string.IsNullOrEmpty(attributeName) || value == null)
        {
            return MvcHtmlString.Empty;
        }

        var render = condition != null ? condition() : true;

        return render ? 
            new MvcHtmlString($"{attributeName}=\"{HttpUtility.HtmlAttributeEncode(value.ToString())}\"") : 
            MvcHtmlString.Empty;
    }

This way you don't have to turn your other datatypes in strings before passing them, saving a fiew .ToString(). There is a difference tho: passing an empty string will still render. As example:

这样您就不必在传递字符串之前将其他数据类型转换为字符串,从而节省了.ToString(). 有一个区别:传递一个空字符串仍然会呈现。例如:

@Html.ConditionalAttr("data-foo", "", () => Model.IsFooNeeded)

// Ouput:
data-foo=""