Search code examples
c#asp.net-mvcurldynamicrouteconfig

MVC 4, create URL dynamic for pages


Let's say I have a model called artikel. this article contains Html "body" text. and a one word title.

Then I want to make a system, where i can use one view to render all of "Article" model's body content.

but use the articles Title prop. to create a Url for the site.

So if i got 2 articles. one titled "About", and one with the title "Contact"

i would end up with Url like "site/About" And "site/Contact"

And since I'm trying to make this from a data source, I need some way to do this dynamic. so i can't just make controllers for each artikel. (Which would be bad if i got many articles anyways)

I been trying in my RouteConfig to setup a mapRoute. but can't find anyway which would do this.

I search the net for it, an tried those solutions.

http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-url-rewriting-and-url-attribute-routing-in-asp-net-mvc-mvc5-with-examples

URL Rewriting in .Net MVC

https://www.youtube.com/watch?v=h405AbJyiH4

https://forums.asp.net/t/2094370.aspx?How+To+Create+URL+Rewrite+In+ASP+NET+C+using+MVC+

But no luck. Anyone that know's how to do this, or that can help me in the right direction.?


Solution

  • There are many ways to solve this problem, for example you can set Artikel to be the default controller, creating new route, or a custom route, etc. I recommend to include artikel in the url website/artikel/pagename for finding the articles.

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            name: "Artikel",
            url: "artikel/{id}",
            defaults: new { controller = "Artikel", action = "Index", id = UrlParameter.Optional }
        );
    
        //default and other routes go here, after Artikel
    }
    

    In Artikel controller:

    public ActionResult Index(string id)
    {
        Artikel model = Database.GetArticle(id);
        return View(model);
    }
    

    Model:

    public class Artikel
    {
        public string Title { get; set; }
        public string Body { get; set; }
    }
    

    And the view:

    @model MyApplication.Models.Artikel
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>@Model.Title</h2>
    <span>@Model.Body</span>