问题
I am trying to link inside the same folder, I have the following structure
/Home/Index
/Home/About
/Home/Contact
When I start the webpage, I link to the Index
, so I get the webpage on the screen: www.example.com
.
Now I would like to link to another page so I get: www.example.com/Contact.html
(or even better I would like to get www.example.com/Contact
) however I get www.example.com/Home/Contact
.
I use this as an action link:
<li class="pure-menu-item pure-menu-selected">@Html.ActionLink("Contact us", "Contact", "Home")</li>
This is my route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
What could I change to get the desired result?
回答1:
Decorate you Contact action with a RouteAttribute and pass it the desired route as parameter (i.e. "Contact")
Edit
Here's an example HomeController using the RouteAttribute:
public class HomeController
: Controller
{
public IActionResult Home()
{
return this.View();
}
[Route("Contact")]
public IActionResult Contact()
{
return this.View();
}
}
Note that you can use the RouteAttribute on Controllers, too. For instance, if I added a Route("Test") attribute on the HomeController, all of my controllers actions would look like: "/Test/[ActionRoute]".
In your views, you can use the following syntax, instead of using the old @Html.ActionLink tag helper:
<li class="pure-menu-item pure-menu-selected">
<a asp-controller="Home" asp-action="Contact">Contact Us</a>
</li>
In my opinion, those attribute tag helpers are way cleaner and html friendly ;)
回答2:
i was able to fix it with some good reading and searching and this is what i came up with:
i added this to the routeConfig for each link to a html page:
routes.MapRoute("Index", "Index", new { controller = "Home", action = "Index" });
routes.MapRoute("About", "About", new { controller = "Home", action = "About" });
routes.MapRoute("Contact", "Contact", new { controller = "Home", action = "Contact" });
and instead of using an action link i use a route link:
<li class="pure-menu-item">@Html.RouteLink("About us", "About")</li>
this gives the desired result: www.example.com/About
来源:https://stackoverflow.com/questions/61235122/asp-net-mvc-keep-links-to-the-root-folder