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

Asp.net mvc ASP.NET MVC razor:HTML中的条件属性,asp.net-mvc,asp.net-mvc-3,razor,Asp.net Mvc,Asp.net Mvc 3,Razor,下面的代码看起来不干净。 有什么改进代码的建议吗 <li @if(ViewData["pagename"].ToString()=="Business details"){ <text>class="active" </text> } > <a @if(ViewData["pagename"].ToString()=="Business details"){ <text>style="color: white; backgr

下面的代码看起来不干净。 有什么改进代码的建议吗

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




  • 您应该用单独的类名替换内联的
    style=“…”
    ,并使用相同的语法


    但是,创建一个单独的HTML帮助程序扩展方法会更简洁,该方法接受一个页面和操作名称,并以通用方式生成HTML。

    MVC具有内置的条件属性

    <div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>
    <div class="@myClass">Content</div>
    
    内容
    内容
    
    如果@myClass为null,它将根本不使用该属性

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

    在MVC4中

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

    
    @{
    字符串css=“class=myDiv”;
    }
    

    这里还有更多内容:

    我使用一个小助手方法,如果值为非空,并且如果定义了布尔函数表达式,则当布尔函数表达式的计算结果为
    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;
    }
    
    public static MvcHtmlString Attr(此HtmlHelper,字符串名称,字符串值,Func条件=null)
    {
    if(string.IsNullOrEmpty(名称)| | string.IsNullOrEmpty(值))
    {
    返回MvcHtmlString.Empty;
    }
    var render=condition!=null?condition():true;
    返回渲染?
    新的MvcHtmlString(string.Format(“{0}=\”{1}\”,名称,HttpUtility.htmlAttributeNCode(value)):
    MvcHtmlString.Empty;
    }
    
    定义后,我可以在Razor视图中使用此方法:

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

    上面的代码将呈现
  • 如果
    示例.isNew==true
    ,如果不是,则将忽略整个
    属性。

    使用标记环绕扩展方法。您的问题代码如下所示:

    @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>
        }
    }
    

    根据此处的解冻答案,采用一个
    对象
    而不是
    字符串

        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;
        }
    
    然后在HTML中

    <li @Html.Raw(classAttr) >  
    
    
    
    也许可以创建一个自定义的HTML帮助程序来呈现包含子链接元素的LI?这很好,比其他一些选项(Razor 2.0选项除外)更简洁。请注意,您的类名不是“活动”的,否则您将具有entry class属性。不知道为什么。当调用传递匿名
    htmlproperty
    对象的html帮助程序时,是否有方法实现相同的null尊重行为?例如,我想有条件地传递属性
    disabled
    ,比如
    @Html.TextBoxFor(lambda,new{disabled=condition?true:null})
    ,但当
    disabled
    null
    时,它仍然呈现
    disabled=”“
    ,这与rendring
    disabled=“anything”相同
    因为当属性存在时,
    禁用
    处于活动状态,而不管值是多少。在这个主题上可以找到,但是现在我想知道还有更好的方法吗?旁注:“data-…”属性不能是有条件的,即使对于null()也不能呈现空值该死!直到现在才知道:-)非常优雅的方式。但是,与
    Func
    lambda不同,我更喜欢一个简单的
    bool?
    参数,因为它更简单:
    我喜欢这种方法,因为当属性名仍然存在时,我应用程序中的许多自定义JavaScript仍然会运行。至少这不会因为属性差异而重复相同的div。谢谢
    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()));
    }
    
    public class DisposableAction : IDisposable
    {
        private readonly Action DisposeAction;
    
        public DisposableAction(Action action)
        {
            DisposeAction = action;
        }
    
        public void Dispose()
        {
            DisposeAction();
        }
    }
    
        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;
        }
    
    @Html.ConditionalAttr("data-foo", "", () => Model.IsFooNeeded)
    
    // Ouput:
    data-foo=""
    
    @{ var classAttr= needClass ? "class=\"class-name\"" : "" }
    
    <li @Html.Raw(classAttr) >