MVC 4,为页面创建URL动态

时间:2018-06-13 11:20:38

标签: c# asp.net-mvc url dynamic routeconfig

假设我有一个名为artikel的模型。 本文包含Html“正文”文本。和一个单词的标题。

然后我想创建一个系统,我可以使用一个视图来渲染所有“文章”模型的正文内容。

但使用文章Title prop。为网站创建网址。

所以,如果我有2篇文章。 一个标题为“关于”,一个标题为“联系人”

我最终会像Url一样 “网站/关于” 和 “现场/联系”

由于我试图从数据源中创建它,我需要一些方法来做这个动态。所以我不能只为每个artikel制作控制器。 (如果我收到很多文章,这将是不好的)

我一直在尝试使用RouteConfig来设置mapRoute。但无论如何都找不到会这样做。

我在网上寻找它,尝试了那些解决方案。

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+

但没有运气。 任何知道如何做到这一点的人,或者能帮助我朝着正确方向前进的人。?

1 个答案:

答案 0 :(得分:0)

有很多方法可以解决这个问题,例如你可以将Artikel设置为默认控制器,创建新路线或自定义路线等。我建议在网址website/artikel/pagename中包含artikel以便查找文章。

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
}

在Artikel控制器中:

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

<强>型号:

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

观点:

@model MyApplication.Models.Artikel
@{
    ViewBag.Title = "Index";
}

<h2>@Model.Title</h2>
<span>@Model.Body</span>