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>
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
:Once defined, I can use this method in my Razor views:
The above code will render
<li class="new">...</li>
ifexample.isNew == true
, if not will omit the entireclass
attribute.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.
MVC has conditional attributes built in...
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!
http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx
Approach with TagWrap extension method. Code for your question would look like this:
TagWrap extension methods
Helper class used for rendering closing tag on Dispose
In MVC4
or
More are here: http://evolpin.wordpress.com/2012/05/20/mvc-4-code-enhancements/