Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to link a cshtml page using href in mvc4

I want to link a Menu.cshtml page using an anchor-tag with an href so that whenever I click on the menu link in the navbar it should direct me to Menu.cshtml. I have tried a few times using this code but i am not able to do it. Here is the code i am using:

<a class="page-scroll" href="~/Views/Home/Menu.cshtml">Menus</a>
like image 929
Nidz Avatar asked Dec 15 '22 11:12

Nidz


2 Answers

You could try to use the ActionLink html helper and let this way the framework to produce the correct link.

@Html.ActionLink("Menus","Menu","Home", null, new { @class = "page-scroll" })
like image 111
Christos Avatar answered Dec 17 '22 00:12

Christos


In ASP.NET MVC you can't directly link to a view. That would defeat the whole purpose of MVC. In ASP.NET MVC, the controllers are responsible for choosing what view to return to the user. You create an actionlink to a controller action and let the action decide what view should be returned to the user. In your case that would be:

@Html.ActionLink("Menus", "Action", "Controller", null, new { @class = "page-scroll" });

Let's say you create a controller named HomeController and an action named Menu. Let's also add a simple action body:

public ActionResult Menu()
{
    return View();
}

Then, by convention ASP.NET MVC would look for a view named Menu.cshtml in Views/Home/. Your actionlink which would link to this action would then be:

@Html.ActionLink("Menus", "Menu", "Home", null, new { @class = "page-scroll" });

Your question is however how to link to a view with href. The @Html.ActionLink will do this for you, but if you really want to use href, you can link to an action instead of a view directly for example (if you're using the default MVC route):

<a class="page-scroll" href="/Home/Menu">Menus</a>
like image 33
Anders Stensaas Avatar answered Dec 17 '22 02:12

Anders Stensaas