MVC Dynamic Views From Url Slug

ぃ、小莉子 提交于 2020-02-02 13:44:26

问题


I am building my first .NET MVC web application and loving the simplicity and flexibility. I have however come to my first stumbling block.

I have a list of items and if you are not logged in you will see a preview link I would like the link to direct to something like below:

/preview/unique-slug

The view should then allow me to display the contents from the database (essentially a details page)

I am not sure how to approach this nor what I should be Google'ing as the results I got were poor.

Any pointers please?


回答1:


This is the way I've done this in the past:

You need to store in the database a column with the slug that each item is referred to by. Then, create a route like the following:

routes.MapRoute("PreviewLink",
    "/preview/{slug}",
    new { controller = "Preview", action = "Details" }
);

So this will call the Details method on the PreviewController like so:

class PreviewController : Controller
{
    public ActionResult Details(string slug)
    {
        var model = db.GetItemBySlug(slug);
        return View("Details", model);
    }
}

Basically, you'll get the slug as a string in your action method, query the database for the item with the corresponding slug, and display it. Essentially, we just replace an integer id with a string slug.

Hopefully that clears things up for you!



来源:https://stackoverflow.com/questions/3099232/mvc-dynamic-views-from-url-slug

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!