0

Say I have my model like so:

public class Book 
{
    public String ID { get; set; }
    public String Title { get; set; }
}

public class Author
{
    public String ID { get; set; }
    public String Name { get; set; }
}

And my RouteConfig defined like so:

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

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

Now, I want to add a slug to the end of each Author route and each Book route. So for example:

/Author/1 => /Author/1/sir-arthur-conan-doyle

/Book/1 => /Book/1/sherlock-holmes

All of my ActionLinks and Url return values are already defined, so while I could go back and add a slug to the MapRoute function and modify each ActionLink individually, I thought, surely there must be a better way.

I want to have the slugs automatically created for me so I don't have to go back and change all the routevalues everywhere I access a book or author. Every time a /Author/1 is referenced, I want it transformed into /Author/1/sir-arthur-conan-doyle on the server. How can I accomplish that?

Community
  • 1
  • 1
CC Inc
  • 5,842
  • 3
  • 33
  • 64
  • If you want the 'name' in the route values (as opposed to a query string value, then you will need to change the definitions to `url: "Book/{id}/{slug}"` etc. But how are you adding the name (are you doing database lookup in each method)? –  Jul 10 '16 at 03:27
  • @StephenMuecke I know I need to add the slug to the route definition, but my question is how do I make MVC add the `Name` as a slug without actually having to add it to each of the routevalues that references them – CC Inc Jul 10 '16 at 03:30
  • 1
    Refer [this answer](http://stackoverflow.com/questions/30349412/how-to-implement-url-rewriting-similar-to-so/30363600#30363600) for an example –  Jul 10 '16 at 03:31
  • @StephenMuecke I'll keep it in mind, but to me it seems ugly having to edit the controller action to add a slug and check it. – CC Inc Jul 10 '16 at 03:33
  • If a user enters `../Book/1` in the adress bar, how would you expect to books name to be appended to the url if its not done in the controller (you could always consider an `ActionFilter`, but its essentially the same) –  Jul 10 '16 at 03:36
  • @StephenMuecke I think an action filter is more what I'm going for, I just don't know how to implement it. – CC Inc Jul 10 '16 at 03:38
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/116903/discussion-between-stephen-muecke-and-cc-inc). –  Jul 10 '16 at 03:39

0 Answers0