开发者

Applying styles programmatically in ASP.NET MVC MasterPage View

开发者 https://www.devze.com 2023-01-27 14:52 出处:网络
What would be the best/most suitable way to achieve the following in my MVC web application ? I have a view called Site.Master (it\'s my MasterPage view), and across the top of this view, I have 5 li

What would be the best/most suitable way to achieve the following in my MVC web application ?

I have a view called Site.Master (it's my MasterPage view), and across the top of this view, I have 5 links, which act as my main site navigation e.g.

<ul>
    <li><a href="">Home</a></li>
    <li><a href="">Links</a></li>
    <li><a href="">Contact Us</a></li>
    ...etc
</ul>

What I want is to be able to highlight the appropriate text link, according to which part of the site the user is currently viewing, so if they were using the 'Contact Us' page, the Contact Us link on the master page view would have a different css style applied to it.

In Web Forms, each of my links was a HyperLink control, and I had a property in the code behind of the MasterPage so assign the relevant CssStyle to each HyperLink control.

What would be the best way to achieve the same thing in my MasterPage view, now I'm 开发者_运维技巧using MVC?


I would probably write an html helper which will generate those menu links and based on the current controller and action will apply a css class current to the anchor:

public static MvcHtmlString MenuLink(
    this HtmlHelper htmlHelper, 
    string linkText, 
    string actionName, 
    string controllerName
)
{
    string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
    string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
    if (actionName == currentAction && controllerName == currentController)
    {
        return htmlHelper.ActionLink(
            linkText,
            actionName,
            controllerName,
            null,
            new {
                @class = "current"
            });
    }
    return htmlHelper.ActionLink(linkText, actionName, controllerName);
}

And then use this helper in my view:

<ul>
  <li><%= Html.MenuLink("Home", "Index", "Home") %></li>
  <li><%= Html.MenuLink("Links", "Links", "Home") %></li>
  <li><%= Html.MenuLink("Contact us", "Contact", "Home") %></li>
</ul> 

Then all that's left is to define this current class in a CSS file to highlight:

.current {
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消