How to work with Action Link when using CSS - asp.net-mvc

<li class="rtsLI" id="Summary"><span class="rtsTxt">Test</span></li>
Above I am replacing with following actionlink:
<li class="rtsLI" >#Html.ActionLink("test1", "Index", new { Area = "Area1", Controller = "controller1" }, new { #class = "rtsLink rtsTxt"})</li> "
At first css is working fine. But when using Actionlink, css not working. Thanks

The standard ActionLink helper always HTML encodes the link text. This means that you cannot use it if you want to render HTML inside. You have 3 possibilities:
Modify your CSS so that you don't need a span inside the link and so that the rtsTxt class could directly be applied to the link
Write a custom ActionLink helper that doesn't HTML encode the text and which would allow you to generate the same markup:
public static class ActionLinkExtensions
{
public static IHtmlString ActionLinkUnencoded(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
object routeValues,
object htmlAttributes
)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var link = new TagBuilder("a");
link.MergeAttributes(new RouteValueDictionary(htmlAttributes));
link.Attributes["href"] = urlHelper.Action(actionName, routeValues);
link.InnerHtml = linkText;
return new HtmlString(link.ToString());
}
}
and then:
<li>
#Html.ActionLinkUnencoded(
"<span class=\"rtsTxt\">User Security</span>",
"index",
new { area = "Tools", controller = "UserSecurity" },
new { #class = "rtsLink" }
)
</li>
Use the Url.Action helper:
<li class="rtsLI">
<a href="#Url.Action("index", new { area = "Tools", controller = "UserSecurity" })" class="rtsLink">
<span class="rtsTxt">User Security</span>
</a>
</li>

Best option will be to use #Url.Action extension method
<li class="rtsLI" id="Summary"><span class="rtsTxt">User Security</span></li>

Write code this way:
<li class="rtsLI" >#Html.ActionLink("<span class='rtsTxt'>User Security</span>", "Index", new { Area = "Tools", Controller = "UserSecurity" }, new { #class = "rtsLink"})</li>`

Related

Razor Html Helpers Actionlink [duplicate]

How can I do something similar to Html.ActionLink() except place the generated link around an Image instead of just spitting out the link?
Razor (View Engine):
<a href="#Url.Action("ActionName", "ControllerName")">
<img src="#Url.Content("~/Content/img/imgname.jpg")" />
</a>
ASPX (View Engine):
<a href="<%= Url.Action("ActionName", "ControllerName") %>">
<img src="<%= Url.Content("~/Content/img/imgname.jpg") %>" />
</a>
Obviously, if you do this more than once, write a helper for it. And fill in the other attributes of img/a. But this should give you the general idea.
Try something like this:
public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName)
{
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
string imgUrl = urlHelper.Content(imgSrc);
TagBuilder imgTagBuilder = new TagBuilder("img");
imgTagBuilder.MergeAttribute("src", imgUrl);
string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing);
string url = UrlHelper.Action(actionName);
TagBuilder tagBuilder = new TagBuilder("a") {
InnerHtml = img
};
tagBuilder.MergeAttribute("href", url);
return tagBuilder.ToString(TagRenderMode.Normal);
}
Hope this helps
The first answer given by #Craig Stuntz is absolutely perfect but my concern is about if what will you do if you have Ajax.ActionLink instead of Html.ActionLink. Here I will explain easy solutions for both methods. You can do as the following for Html.ActonLink:
#Html.Raw(#Html.ActionLink("[replacetext]", "Index", "Home").ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" ... />"))
same concept can be applied for Ajax.ActionLink
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/Contents/img/logo.png\" … />"))
so this will be easy for you.
Edit:
ActionLink Image with Style Sheet or Class Name
With Style sheet
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" style=\"width:10%\" ... />"))
With Class Name
<style>
.imgClass {
width:20%
}
#Html.Raw(#Ajax.ActionLink("[replacetext]", "Index", "Home", new AjaxOptions { UpdateTargetId="dvTest"}).ToHtmlString().Replace("[replacetext]", "<img src=\"/assets/img/logo.png\" class=\"imgClass\" ... />"))
For more reference regarding ActionLink around Image visit ActionLink around Image in Asp.net MVC
more easy...
change your code by:
<p class="site-title">#Html.ActionLink(" ", "Index", "Home",
new
{
style = "background: url('" + Url.Content("~/images/logo.png") + "') no-repeat center right; display:block; height:50px;width:50px;"
})</p>
You can use url.content:
#Url.Content("~/images/img/slide.png")
this return relative path
You can create htmlhelper which can return image with link...
As parameters you will pass to htmlhelper values like image path and link and in htmlhelper you will use StringBuilder to format html of that linked image properly...
cheers

ASP.NET Actionlink with glyphicon and text with different font

I want to present a button with #Html.ActionLink but i need to have my application font in the text.
With this code:
<span>
#Html.ActionLink(" Create New", "Create", null, new { #class = "btn btn-warning glyphicon glyphicon-plus-sign" })
</span>
I get my button but the Create New text appears with the glyphicon font-family.
Putting the glyphicon classes in the span doesn't change anything
You should not add the glyphicon class to the a-tag.
From the Bootstrap website:
Don't mix with other components
Icon classes cannot be directly combined with other components. They should not be used along with other classes on the same element. Instead, add a nested <span> and apply the icon classes to the <span>.
Only for use on empty elements
Icon classes should only be used on elements that contain no text content and have no child elements.
In other words the correct HTML for this to work the way you want would be: test <span class="glyphicon glyphicon-plus-sign"></span>
This makes the Html.ActionLink helper unsuitable. Instead you could use something like:
<a href="#Url.Action("Action", "Controller")" class="btn btn-warning">
link text
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</a>
This works for me in MVC 5:
#Html.ActionLink(" ", "EditResources", "NicheSites", new { ViewBag.dbc, item.locale, ViewBag.domainId, domainName = ViewBag.domaiName }, new {#class= "glyphicon glyphicon-edit" })
The first parameter cannot be empty or null or it will blow.
It might be better to just write out the HTML rather than try to make it work with HtmlHelper.ActionLink...
<span>
<a href="#Url.Action("Create")" class="btn btn-warning">
<span class="glyphicon glyphicon-plus-sign"></span>
Create New
</a>
</span>
Here's mine. Inspired by Andrey Burykin
public static class BensHtmlHelpers
{
public static MvcHtmlString IconLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, String iconName, object htmlAttributes = null)
{
var linkMarkup = htmlHelper.ActionLink(linkText, actionName, routeValues, htmlAttributes).ToHtmlString();
var iconMarkup = String.Format("<span class=\"{0}\" aria-hidden=\"true\"></span>", iconName);
return new MvcHtmlString(linkMarkup.Insert(linkMarkup.IndexOf(#"</a>"), iconMarkup));
}
}
I should go with the approach of #Url.Action instead of #Html.ActionLink, se example code below:
<span>
<span class="glyphicon glyphicon-plus-sign"></span> Create New
</span>
You can use simple extension:
private static readonly String SPAN_FORMAT = "<span class=\"{0}\" aria-hidden=\"true\"></span>";
private static readonly String A_END = "</a>";
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, String iconName, object htmlAttributes = null)
{
var linkMarkup = htmlHelper.ActionLink(linkText, actionName, routeValues, htmlAttributes).ToHtmlString();
if (!linkMarkup.EndsWith(A_END))
throw new ArgumentException();
var iconMarkup = String.Format(SPAN_FORMAT, iconName);
return new MvcHtmlString(linkMarkup.Insert(linkMarkup.Length - A_END.Length, iconMarkup));
}
Usage:
Html.ActionLink(" ", "DeleteChart", new { Id = _.Id }, "glyphicon glyphicon-trash")
Try it!
#Html.ActionLink(" Cerrar sesión", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" , #class = "glyphicon glyphicon-log-in" })
Let's have a try on this. Let me know if it is working .Thanks
<style>
span.super a
{
font: (your application font) !important;
}
</style>
<span class="super">
#Html.ActionLink(" Create New", "Create", null, new { #class = "btn btn-warning glyphicon glyphicon-plus-sign" })
</span>
How about using Html.BeginForm with a FormMethod.Get / FormMethod.Post
#using (Html.BeginForm("Action", "Controller", new { Area = "" },
FormMethod.Get, htmlAttributes: new { title = "SomeTitle" }))
{
<button type="submit" class="btn-link" role="menuitem">
<i class="glyphicon glyphicon-plus-sign"></i>Create New</button>
}
Try this. Worked for me.
<button class="btn btn-primary"><i class ="fa fa-plus">#Html.ActionLink(" ", "Create", "Home")</i></button>

Image button in ActionLink MVC

How to put image instead text in ActionLink button:
#Html.ActionLink("Edit-link", "Edit", new { id=use.userID })
So how to change text "Edit-link" to image?
Thanks for any idea.
do like this:
<a href="#Url.Action("Edit")" id="#use.userID">
<img src="#Url.Content("~/images/someimage.png")" />
</a>
or pass both action and controller name by using other override:
<a href="#Url.Action("Edit","Controller")" id="#use.userID">
<img src="#Url.Content("~/images/someimage.png")" />
</a>
UPDATE:
You can also create a custom Html Helper, and can reuse it in any View in application:
namespace MyApplication.Helpers
{
public static class CustomHtmlHelepers
{
public static IHtmlString ImageActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes,string imageSrc)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var img = new TagBuilder("img");
img.Attributes.Add("src", VirtualPathUtility.ToAbsolute(imageSrc));
var anchor = new TagBuilder("a") { InnerHtml = img.ToString(TagRenderMode.SelfClosing) };
anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return MvcHtmlString.Create(anchor.ToString());
}
}
}
and use it in View:
#using MyApplication.Helpers;
#Html.ImageActionLink("LinkText","ActionName","ControllerName",null,null,"~/images/untitled.png")
Output HTML:
<a href="/ControllerName/ActionName">
<img src="/images/untitled.png">
</a>
Try this code :
#Html.Raw(#Html.ActionLink("Edit-link","Edit", new { id=use.userID }).ToHtmlString().Replace("Edit-link", "<img src=\"/Contents/img/logo.png\" ... />"))
or
<a href="#Url.Action("Edit Link","Edit",new {id = item.EId })">
<img src="#Url.Content("~/img/iconfinder_new-24_103173.png")" style="height:20px;width:20px;color:blue" title="Edit" />
</a>
Try this code. It will add an image linked to the Edit() action with the id set.

Convert HREF to RouteLink

It seems to be simple, but I can't get anything to work. This code was generated by my template generator and needs to be changed.
<li><a href="../Home/Contact" class="active"><span class="l"></span><span class="r">
</span><span class="t">Nous contacter</span></a> </li>
My best bet up to now is:
<li><span class="l"></span><span class="r"></span>
#Html.RouteLink("Contact", new { Controller = "Home", Action = "Contact" }, new { #class = "t" })</li>
But it doesn't do anything.
Just to make sur that my question is clear: The link works in both cases, that's fine. The formating doesn't work. That's my issue here.
The second will generate:
<li>
<span class="l"></span>
<span class="r"></span>
<a class="t" href="/Home/Contact">Contact</a>
</li>
which is different than what you had in the first place which might explain the formatting problems:
<li>
<a href="../Home/Contact" class="active">
<span class="l"></span>
<span class="r"></span>
<span class="t">Nous contacter</span>
</a>
</li>
The problem with Html helpers such as Html.ActionLink and RouteLink is that they by always Html encode the text, so you cannot use HTML as text. So one possibility is the following:
<li>
<a href="#Url.RouteUrl("Contact", new { controller = "home", action = "contact" })" class="active">
<span class="l"></span>
<span class="r"></span>
<span class="t">Nous contacter</span>
</a>
</li>
Another possibility if you have lots of those to generate is to write a custom Html helper that will do the job for you:
public static class HtmlExtensions
{
public static IHtmlString MyLink(
this HtmlHelper htmlHelper,
string linkText,
string routeName,
object routeValues
)
{
var spans = string.Format(
"<span class=\"l\"></span><span class=\"r\"></span><span class=\"t\">{0}</span>",
htmlHelper.Encode(linkText)
);
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.RouteUrl(routeName, routeValues);
var anchor = new TagBuilder("a");
var rvd = new RouteValueDictionary(routeValues);
var rd = htmlHelper.ViewContext.RouteData;
var currentAction = rd.GetRequiredString("action");
var currentController = rd.GetRequiredString("controller");
var controller = rvd["controller"] as string;
var action = rvd["action"] as string;
if (string.Equals(controller, currentController, StringComparison.OrdinalIgnoreCase) &&
string.Equals(action, currentAction, StringComparison.OrdinalIgnoreCase))
{
anchor.AddCssClass("active");
}
anchor.Attributes["href"] = url;
anchor.InnerHtml = spans;
return new HtmlString(anchor.ToString());
}
}
and then:
<li>
#Html.MyLink("Nous contacter", "Contact", new { controller = "home", action = "contact" })
</li>
Just use something like this:
#Url.Action("Index", "Home")

Adding "active" tag to navigation list in an asp.net mvc master page

In the default asp.net mvc project, in the Site.Master file, there is a menu navigation list:
<div id="menucontainer">
<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li><%= Html.ActionLink("About Us", "About", "Home")%></li>
</ul>
</div>
This renders in the browser to:
<div id="menucontainer">
<ul id="menu">
<li>Home</li>
<li>About Us</li>
</ul>
</div>
I want to be able to dynamically set the active list item, based on the view that is being called. That is, when the user is looking at the home page, I would want the following HTML to be created:
<div id="menucontainer">
<ul id="menu">
<li class="active">Home</li>
<li>About Us</li>
</ul>
</div>
I would expect that the way to do this would be something like:
<div id="menucontainer">
<ul id="menu">
<li <% if(actionName == "Index"){%> class="active"<%}%>><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li <% if(actionName == "About"){%> class="active"<%}%>><%= Html.ActionLink("About Us", "About", "Home")%></li>
</ul>
</div>
The key bit here is the <% if(actionName == "Index"){%> class="active"<%}%> line. I do not know how to determine what the current actionName is.
Any suggestions on how to do this? Or, if I'm on completely the wrong track, is there a better way to do this?
I made myself a helper method to handle this type of thing. In the code behind of my master page (could be pushed of to an extension method ... probably a better approach), I put the following code.
protected string ActiveActionLinkHelper(string linkText, string actionName, string controlName, string activeClassName)
{
if (ViewContext.RouteData.Values["action"].ToString() == actionName &&
ViewContext.RouteData.Values["controller"].ToString() == controlName)
return Html.ActionLink(linkText, actionName, controlName, new { Class = activeClassName });
return Html.ActionLink(linkText, actionName, controlName);
}
Then, I just call it in my page like so:
<%= ActiveActionLinkHelper("Home", "Index", "Home", "selected")%>
Inside a view, you can get the current action name with:
ViewContext.RouteData.Values["action"].ToString()
You can also try to detect which is the current selected tab from its controller name and view name, then add the class attribute.
public static string MenuActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName)
{
var htmlAttributes = new RouteValueDictionary();
if (helper.ViewContext.Controller.GetType().Name.Equals(controllerName + "Controller", StringComparison.OrdinalIgnoreCase))
{
htmlAttributes.Add("class", "current");
}
return helper.ActionLink(linkText, actionName, controllerName, new RouteValueDictionary(), htmlAttributes);
}
In MVC 3 Razor View Engine, you can do it as:
#{string ctrName = ViewContext.RouteData.Values["controller"].ToString();}
<div id="menucontainer">
<ul id="menu">
<li #if(ctrName == "Home"){<text> class="active"</text>}># Html.ActionLink("Home", "Index", "Home")</li>
<li #if(ctrName == "About"){<text> class="active"</text>}># Html.ActionLink("About Us", "About", "Home")</li>
</ul>
</div>
My sample worked when I have two pages as: Home/About and its controller has same name Index, so I get controller Name for distinction insteed of action. If you want to get action, just replace with following:
#{string ctrName = ViewContext.RouteData.Values["action"].ToString();}
An old question but hopefully someone might find this very helpful.
Put some thing that you can use to identify your page in the ViewBag, I used ViewgBag.PageName
For example, in index.cshtml, put something like
#{
ViewBag.PageName = "Index";
}
Add a class to each link item with a conditional statement to return active if the page being visited has the required value, or return an empty string otherwise. View below for details:
<li class="#((ViewBag.PageName == "Index") ? "active" : "")">Home</li>
<li class="#((ViewBag.PageName == "About") ? "active" : "")">About</li>
<li class="#((ViewBag.PageName == "Contact") ? "active" : "")">Contact</li>
I didn't just test it, I use this method in my projects
To contribute my own answer (tested in MVC4), I took a few best bits of the other answers, fixed a few issues, and added a helper to work with urls that aren't necessarily resolved via Controller & Action (eg. if you have an embedded CMS dealing with some page links, etc.)
The code is also forkable on github: https://gist.github.com/2851684
///
/// adds the active class if the link's action & controller matches current request
///
public static MvcHtmlString MenuActionLink(this HtmlHelper htmlHelper,
string linkText, string actionName, string controllerName,
object routeValues = null, object htmlAttributes = null,
string activeClassName = "active")
{
IDictionary htmlAttributesDictionary =
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (((string)htmlHelper.ViewContext.RouteData.Values["controller"])
.Equals(controllerName, StringComparison.OrdinalIgnoreCase) &&
((string)htmlHelper.ViewContext.RouteData.Values["action"])
.Equals(actionName, StringComparison.OrdinalIgnoreCase))
{
// careful in case class already exists
htmlAttributesDictionary["class"] += " " + activeClassName;
}
return htmlHelper.ActionLink(linkText, actionName, controllerName,
new RouteValueDictionary(routeValues),
htmlAttributesDictionary);
}
///
/// adds the active class if the link's path matches current request
///
public static MvcHtmlString MenuActionLink(this HtmlHelper htmlHelper,
string linkText, string path, object htmlAttributes = null,
string activeClassName = "active")
{
IDictionary htmlAttributesDictionary =
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (HttpContext.Current.Request.Path
.Equals(path, StringComparison.OrdinalIgnoreCase))
{
// careful in case class already exists
htmlAttributesDictionary["class"] += " " + activeClassName;
}
var tagBuilder = new TagBuilder("a")
{
InnerHtml = !string.IsNullOrEmpty(linkText)
? HttpUtility.HtmlEncode(linkText)
: string.Empty
};
tagBuilder.MergeAttributes(htmlAttributesDictionary);
tagBuilder.MergeAttribute("href", path);
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
Using MVC3 with a Razor View offers another option:
_Layout.cshtml:
<li class="#ViewBag.NavClassHome">#Html.ActionLink("Home", "Index", "Home")</li>
<li class="#ViewBag.NavClassAbout">#Html.ActionLink("Disclaimer", "About", "Home")</li>
HomeController:
public ActionResult Index() {
ViewBag.NavClassHome = "active";
return View();
}
public ActionResult About() {
ViewBag.NavClassAbout = "active";
return View();
}
If you want to preserve this for a postback as well, you have to assign the ViewBag value here as well:
[HttpPost]
public ActionResult Index() {
ViewBag.NavClassHome = "active";
return View();
}
[HttpPost]
public ActionResult About() {
ViewBag.NavClassAbout = "active";
return View();
}
Tested and working fine for me, but you will have a css class name in your server side code.
This should work using jQuery on the client side of things, uses Google to serve the latest jQuery library:
<script src="http://www.google.com/jsapi" type="text/javascript" language="javascript"></script>
<script type="text/javascript" language="javascript">google.load("jquery", "1");</script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
var str=location.href.toLowerCase();
$('#menucontainer ul#menu li a').each(function() {
if (str.indexOf(this.href.toLowerCase()) > -1) {
$(this).attr("class","current"); //hightlight parent tab
}
});
});
</script>
I wanted to have a bit more control over my layout, and this is what I did.
Create a LayoutModel that other models inherit:
public abstract class LayoutModel
{
public CurrentPage CurrentPage { get; set; }
}
Create a LayoutAttribute that inherits from ActionFilterAttribute like so:
public class LayoutAttribute : ActionFilterAttribute
{
private CurrentPage _currentPage { get; set; }
public LayoutAttribute(
CurrentPage CurrentPage
){
_currentPage = CurrentPage;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var result = filterContext.Result as ViewResultBase;
if (result == null || result.Model == null || !(result.Model is LayoutModel)) return;
((LayoutModel)result.Model).CurrentPage = _currentPage;
}
}
Now on the Action or Controller level I can set the current page (and other stuff if I wanted) like this:
[Layout(CurrentPage.Account)]
public class MyController : Controller
{
}
In my layout view I now have access to the current page, and whatever else I add to the LayoutModel.
The fact that your View has to know about your controller's actions is breaking with the MVC pattern. Perhaps your controller could pass some "control" information to the view to ultimately allow it to accomplish the same thing, the only difference is who is in charge.
Like in your controller's action you could:
public ActionResult Index(){
ViewData["currentAction"] = "Index";
//... other code
return View();
}
Then over in your view you could:
<% if( ((string)ViewData["currentAction"]) == "Index" {%> <!- some links --><% } %>
<% if( ((string)ViewData["currentAction"]) == "SomethingElse" {%> <!- some links --><% } %>
However, the more I think about it the more I question why you are using the same View for multiple actions. Is the view that similar?
If the use case justifies it then go with my above suggestion. But otherwise perhaps you could break things out into multiple views (one for each controller action) and the problem solves itself.
Based on the previous answers, here is what my current solution is for the same issue:
In the master page I give each li an id that corresponds to the controller and the action, since this should be known from the ActionLink. I was previously doing this with the page title but this helps with organization.
Site.Master:
<ul id="menu">
<li id="menuHomeIndex" runat="server"><%= Html.ActionLink("Home", "Index", "Home") %></li>
<li id="menuHomeAbout" runat="server"><%= Html.ActionLink("About Us", "About", "Home") %></li>
</ul>
Site.Master.cs:
// This is called in Page_Load
private void SetActiveLink()
{
string action = "" + ViewContext.RouteData.Values["controller"] + ViewContext.RouteData.Values["action"];
var activeMenu = (HtmlGenericControl)Page.Master.FindControl("menu" + action);
if (activeMenu != null)
{
activeMenu.Attributes.Add("class", "selected");
}
}
It's more work than the inline code but I think it's cleaner and also lets you have actions with the same name in different controllers. So if you add more menu items with different controllers, not all actions named Index will be highlighted in the menu.
If anyone sees issues with this approach please let me know.
Using MVC3 with a Razor View, you can implement this like:
<ul id="menu">
#if (ViewContext.RouteData.Values["action"].ToString() == "Index")
{
<li class="active">#Html.ActionLink("Home", "Index", "Home")</li>
}
else
{
<li>#Html.ActionLink("Home", "Index", "Home")</li>
}
#if (ViewContext.RouteData.Values["action"].ToString() == "About")
{
<li class="active">#Html.ActionLink("About", "About", "Home")</li>
}
else
{
<li>#Html.ActionLink("About", "About", "Home")</li>
}
</ul>
And then applying your style of your ".active" class like:
ul#menu li.active
{
text-decoration:underline;
}
Here is the version compatible with the current version of MVC4.
I have rewritten Adam Carr's code as an extension method.
using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
namespace MyApp.Web {
public static class HtmlHelpers {
/// <summary>
/// Returns an anchor element (a element) that contains the virtual path of the
/// specified action. If the controller name matches the active controller, the
/// css class 'current' will be applied.
/// </summary>
public static MvcHtmlString MenuActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName) {
var htmlAttributes = new RouteValueDictionary();
string name = helper.ViewContext.Controller.GetType().Name;
if (name.Equals(controllerName + "Controller", StringComparison.OrdinalIgnoreCase))
htmlAttributes.Add("class", "current");
return helper.ActionLink(linkText, actionName, controllerName, new RouteValueDictionary(), htmlAttributes);
}
}
}
Hope this will help.
<ul>
<li class="#(ViewContext.RouteData.Values["Controller"].ToString() == "Home" ? "active" : "")">
<a asp-area="" asp-controller="Home" asp-action="Index"><i class="icon fa fa-home"></i><span>Home</span>
</a>
</li>
</ul>
Try
Should work fine !!!
EDIT : REMOVED IN BETA1
Removed the ViewName property from the ViewContext class.

Resources