Home > database >  How to access url with custom route pattern?
How to access url with custom route pattern?

Time:12-04

I have set my pattern to this:

endpoints.MapControllerRoute(
            //name: "default",
            //pattern: "{controller=Home}/{action=Index}/{id?}");
            name: "custom",
            pattern: "{company?}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();

When I access the url vie browser like https://localhost:44387/123/Users the page will successfuly displayed and the value 123 successfully retrive in the controller:

public IActionResult Index(string company)
{
    //code here
}

How can I access this via razor? before the I updated the pattern, I only use the default like this code

<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="123/Users" asp-action="Index">User</a>
</li>
<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Clients" asp-action="Index">Client</a>
</li>

I tried appending 123 to the asp-controller but it does not work. What am I missing here? Thanks!

CodePudding user response:

You can use:

<li class="nav-item">
    <a class="nav-link text-dark" href="\123\Users\Index">User</a> 
</li>

Or use the HTML helper method:

<li class="nav-item">
    @Html.ActionLink("Users", "Index", "Users", routeValues: new { company = "123" }, htmlAttributes: new { @class= "nav-link text-dark" })
</li>

For more information see HtmlHelperLinkExtensions.ActionLink Method

  • Related