0

I have this mvc route defined.

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

so my url will be something like this:

http://mysitename.com/Author/AuthorName - this should bring all quotes of the particular author. http://mysitename.com/Author/Authorname/QuoteID - this should bring a particular quote of that author.

My controller name is author controller. Is this feasible? If so how should I define the routes and action methods to accomplish this?

Venkat
  • 1,702
  • 2
  • 27
  • 47
  • What do you mean _without defining an action_? And that route definition will not produce either of those urls. –  Jun 02 '17 at 10:14
  • How should the route be defined then? – Venkat Jun 02 '17 at 10:17
  • Do you have 2 action methods, one that accepts the author name (for all quotes associated with that author) and a separate method to return a view for a specific QuoteID? –  Jun 02 '17 at 10:19
  • No I donot have any except the default Index(). – Venkat Jun 02 '17 at 10:21
  • And I assume you do not want the word `Index` in the route (which will be the case with your current route (and the answer just added). –  Jun 02 '17 at 10:24
  • I assume this brings down to http://mysitename.com/Author/Quote/AuthorName Is it not possible to have http://mysitename.com/Author/AuthorName ? – Venkat Jun 02 '17 at 10:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/145712/discussion-between-stephen-muecke-and-venkat). –  Jun 02 '17 at 10:27
  • @Venkat Which version of ASP .NET MVC are you using? – mridula Jun 02 '17 at 10:43
  • System.web.MVC points to 4.0 – Venkat Jun 02 '17 at 10:44
  • @mridula can you give me your answer. I will try. – Venkat Jun 02 '17 at 11:19

1 Answers1

2

You would typically have 2 separate methods, one for the list of Quotes, and another for the details of a specific quote. Assuming they are

public ActionResult Quotes(string author)

and

public ActionResult QuoteDetails(string author, int id)

the your route definitions would be

routes.MapRoute(
    name: "AuthorQuotes",
    url: "Author/{author}",
    defaults: new { controller = "Author", action = "Quotes" }
);

routes.MapRoute(
    name: "QuoteDetails",
    url: "Author/{author}/{id}",
    defaults: new { controller = "Author", action = "QuoteDetails" }
);

and both these need to be before the default route.

As a side note, the author name is not necessary for the 2nd route and you could just use the id parameter, and consider using a 'slug' route for the author name (refer this answer for an example