2

i have project with Map Route (that's all):

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

and I have method in controller:

public ViewResult List(int id = 1)
{
  ...
}

and in List.cshtml:

@Html.ActionLink(i.ToString(), "List", "Product", new { id = i }, null)

but i want to change id to page, but not change it in RouteConfig.cs, i think that's some attribute which can config my route for action. I want this solution:

@Html.ActionLink(i.ToString(), "List", "Product", new { page = i }, null)

and

[maybe here I can add my specify route?]
public ViewResult List(int page = 1)
{
  ...
}

1 Answer 1

2

You can use attribute routing to override the convention.

First make sure attribute routing is enabled:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapMvcAttributeRoutes();   

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

Then add appropriate attribute to your controller method, for example:

[Route("YourControllerName/List/{page?}")]
public ViewResult List(int page = 1)
{
    ...
}

Question mark makes the page parameter optional.

If it's a default controller and action

[Route("")]
[Route("YourControllerName/List/{page?}")]
public ViewResult List(int page = 1)
{
    ...
}

More about attribute routing can be found here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.