Imad
Imad

Reputation: 7490

Default Route with parameters

I have created a controller and I don't want my default Action or View to be named Index. I created Action in TopicsController as below

[ActionName("Index")]
public ActionResult Topics()
{
    var topic = new Topic();
   return View("Topics", topic.GetTopics());
}

and it mached to URL xyz.com/Topics.

I tried to apply same philosophy to another controller, named, ModulesController but now I have got parameter.

[ActionName("Index")]
public ActionResult Modules(string id)
{
    var topic = new Topic();
    return View("Modules", topic.GetTopics());
}

but now it is saying

The resource cannot be found.

what I can do so that this action matches URL like xyz.com/Modules/aaaa?

Upvotes: 0

Views: 169

Answers (1)

Md Rahatur Rahman
Md Rahatur Rahman

Reputation: 3246

To access the Url xyz.com/Modules/aaaa change the Action name for the Modules action to aaaa like this:

[ActionName("aaaa")]
public ActionResult Modules(string id)
{
    var topic = new Topic();
    return View("Modules", topic.GetTopics());
}

FYI - It would be better to avoid naming each action with the ActionName filter. At some point it would become difficult to manage. Instead manage the routes in the RouteConfig like this:

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

The following Urls will work for the above route:

  • xyz.com/Modules/aaaa
  • xyz.com/Modules/aaaa/123
  • xyz.com/Modules/aaaa?id=123

Update: If you want 'aaaa' to be the parameter and want to access the action with xyz.com/Modules/aaaa (where 'aaaa' will be bound as the value to the Id variable) then add the following Route to the route table:

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

Note the value of the Url above.

Upvotes: 1

Related Questions