Stian
Stian

Reputation: 1602

How do I configure routing with two optional route values?

This is my route config in Startup.cs:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}/{tab?}");
});

Some of my views make use of both id and tab, some just id and some just tab.

id is of type Guid, and tab is of type int.

How can I configure my routing to eliminate the id-part (/0) in the following url to a view which does not make use of it?

/Home/Index/0/3 // id is not relevant, tab = 3

In this case, I have to set id to 0 in order for the url to work. This is an index-view with sub sections organized in tabs.

Upvotes: 1

Views: 1088

Answers (3)

dotnetstep
dotnetstep

Reputation: 17485

For this you can do something like. As per your comment Id is guid and tab is int.

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                  name: "onlyid",
                  pattern: "{controller=Home}/{action=Index}/{id:guid}", new { tab = default(int) });

                endpoints.MapControllerRoute(
                   name: "onlytab",
                   pattern: "{controller=Home}/{action=Index}/{tab:int}", new { id = default(Guid) } );

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id:Guid}/{tab:int}");
            });

Now if there is only tab then onlyTab will get choose and it has default value for Guid ( Guid.Empty) but you can address like /Home/Index/1 .

If there is only id then onlyId will get selected and it has default value for integer. Home/Index/yourguid

If you pass both then third route get selected.

Method as Controller look like following.

 public IActionResult Index(Guid? id,int? tab)
        {
            return Ok(new { Id = id, Tab = tab });
        }

Upvotes: 2

Stian
Stian

Reputation: 1602

This seems to do the trick:

[Route("Home/{tab?}")]
public async Task<IActionResult> Index(string tab)
{
    // do stuff
}

Upvotes: 0

Anoob
Anoob

Reputation: 13

Please try this code

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}/{tab}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, tab= UrlParameter.Optional }
            );
        }

enter image description here

enter image description here this like we can pass variable type and reference type parameter

Upvotes: 0

Related Questions