1

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.?

DaCh
  • 921
  • 1
  • 14
  • 48
  • check this article may be That's what you want or give you another idea – Ali Besharati Jun 13 '18 at 11:31
  • @AliBesharatinia sorry. but did you forget to post the link? – DaCh Jun 13 '18 at 11:32
  • The problem is, that url `site/About` would override any other. How do you know About is not a controller? – derloopkat Jun 13 '18 at 13:35
  • Is it good enough to have example.com/artikel/About and example.com/artikel/Contact etc? or do you need example.com/About. If it's the former you can have an action that gets the article name as a route parameter. You could then retrieve the appropriate page from your data source and render it somehow. – Baffour Jun 13 '18 at 14:02

1 Answers1

0

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>
derloopkat
  • 6,232
  • 16
  • 38
  • 45