Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC razor: conditional attribute in HTML

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> 
like image 777
Mahesh Avatar asked Feb 22 '12 17:02

Mahesh


4 Answers

MVC has conditional attributes built in. For example:

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

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

See also: John Galloway's blog post on ASP.NET MVC 4 Beta > Conditional attribute rendering

like image 108
jcreamer898 Avatar answered Nov 19 '22 12:11

jcreamer898


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

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

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.

like image 42
SLaks Avatar answered Nov 19 '22 10:11

SLaks


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:

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:

<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 class attribute.

like image 24
defrost Avatar answered Nov 19 '22 11:11

defrost


@{ var classAttr= needClass ? "class=\"class-name\"" : "" }

and then in the HTML

<li @Html.Raw(classAttr) >  
like image 6
user4649102 Avatar answered Nov 19 '22 12:11

user4649102