I am using HtmlHelper class where i used some code and i set this to my layout Navbar as menu.
Below is the code for the same:
public static MvcHtmlString MenuLink(this HtmlHelper helper,string text, string action, string controller)
{
var routeData = helper.ViewContext.RouteData.Values;
var currentController = routeData["controller"];
var currentAction = routeData["action"];
if (String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase))
{
return new MvcHtmlString("<li class=\"nav-item active\">" + helper.ActionLink(text, action, controller, new { @class="nav-link" }) + "</li>");
}
return new MvcHtmlString("<li class=\"nav-item\">" + helper.ActionLink(text, action, controller, new { @class = "nav-link" }) + "</li>");
}
And i set my menu like below in Layout page:
@Html.MenuLink("Search", "Search", "Home")
Now when i run application it first load the login page where login path is : Account/Login
Now in the search menu when i hover this menu then i found like this menu url is also set like Account/Search?Length=4.
But i passed "Home" controller for this menu.
I debug the html helper class code and found like it set the correct action and controller which is passed from layout.
Don't know where this url is get changed.
Please suggest.
Use following code :
public static MvcHtmlString MenuLink(this HtmlHelper helper,string text, string action, string controller)
{
var routeData = helper.ViewContext.RouteData.Values;
var currentController = routeData["controller"];
var currentAction = routeData["action"];
if (String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase))
{
return new MvcHtmlString("<li class=\"nav-item active\">" + helper.ActionLink(text, action, controller,null, new { @class="nav-link" }) + "</li>");
}
return new MvcHtmlString("<li class=\"nav-item\">" + helper.ActionLink(text, action, controller,null, new { @class = "nav-link" }) + "</li>");
}
When you use
helper.ActionLink(text, action, controller,new { @class="nav-link" })
then it refers to current controller because you have not specified routeValue so, when you want to redirect from one controller to other then specify routevalue as null if there is no routevalue to redirect method.
So, Use helper.ActionLink(text, action, controller,null, new { @class="nav-link" })