J86
J86

Reputation: 15237

A property on entity as route value in ASP.NET MVC

I am working on a new project in ASP.NET MVC 5. On many cool website, you often see routes like this:

www.website.com/artist/vincent-van-gogh/wiki

www.website.com/artist/vincent-van-gogh/paintings

So imagine I have an Entity Artist that looks like this:

namespace BB.DOMAIN.Entities
{
    public class Artist
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

And I want to view the details of any given artist by the .Name property in the URL, like shown above?

Is there a way I can achieve this in ASP.NET MVC without creating thousands of unique routes?

Upvotes: 1

Views: 128

Answers (1)

DLeh
DLeh

Reputation: 24395

You would have a route something like this:

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{artistName}/{action}",
        defaults: new { controller = "Artist", action = "Index" }
    );

Then in your ArtistController you'd have a an action like this:

public ActionResult Wiki(string artistName)
{
    var artist = MyContext.Artists.SingleOrDefault(x => x.Name == artistName);
    //now you have the artist you want.
}

Upvotes: 1

Related Questions