MVC Attribute Routing with Scope Querystring Parameter

I tried to add Route attribute to our controller using various methods.

[Route("Trials/{trialId:int}/Components/{action}")]
public partial class ComponentsController : Controller
{
    public virtual ActionResult List(int trialId)
    {
        return View();
    }
}

      

or

[RoutePrefix("Trials/{trialId:int}/Components")]
[Route("{action=List}")]
public partial class ComponentsController : Controller
{
    public virtual ActionResult List(int trialId)
    {
        return View();
    }
}

      

are just a few examples.

The generated links to this controller / action look like this:

http: // localhost: 50077 / Trials / 3 / Components? Area =

I want to remove a query string parameter. No matter how I place my route config with attributes, it never works.

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

        routes.MapMvcAttributeRoutes();

        //routes.MapRoute(
        //    name: "TrialComponents",
        //    url: "Trials/{trialId}/Components/{action}/{id}",
        //    defaults: new {controller = "Components", action = "List", area = "", id = UrlParameter.Optional},
        //    constraints: new { trialId = "\\d+"}
        //);

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "UnitGroups", action = "List", area = "", id = UrlParameter.Optional }
        );
    }
}

      

The recorded route works and does not apply the request to the url.

Can someone please explain why the route method adds a Querystring Area and how can I fix it? I'm stumped.

+3


source to share


1 answer


Area is not the route value that is stored in the collection RouteData.Values

, it is instead in the collection RouteData.DataTokens

(as metadata). It is wrong to set the default for area

in RouteCollection

, because this only applies to the RouteData.Values

request.

Long story short, to remove a parameter area

from the generated urls, you need to remove it as the default in MapRoute

.



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

      

0


source







All Articles