How to add page title in url in asp.net mvc? (url generation)

被刻印的时光 ゝ 提交于 2019-11-28 09:07:04

You have to use something as follows.

Routes.MapRoute(
    "Post",
    "posts/{id}/{*title}",
    new { controller = "Posts", action = "view" }
);

And a simple extension method:

public static class UrlExtensions
{

    public static string ResolveSubjectForUrl(this HtmlHelper source, string subject)
    {
        return Regex.Replace(Regex.Replace(subject, "[^\\w]", "-"), "[-]{2,}", "-");
    }

}
womp

I've always stored slugs in the database alongside whatever entity would be referenced by them. So for a blog post, you would have a "slug" field in the "posts" table.

To handle it in ASP.Net MVC is easy - you just use a regular route that would capture the slug in a parameter (possibly even just using {id}), and then your controller would look up the slug in the database, load the entity, and display it as normal.

Although you can use a simple RegEx to replace spaces and whatnot to generate your slugs, in reality this breaks down pretty quickly. You need to consider all kinds of characters that may appear in your titles. Michael Kaplan's blog has been linked to heavily for this exact purpose; he's shared a function that will strip diacritical marks from strings.

So, your "generate slug" algorithm should generally take the form of:

  1. Trim the string of leading/trailing whitespace
  2. Strip diacritical marks using Michael Kaplan's function or equivalent
  3. Lowercase the string for canonicalization
  4. Replace all the non-word characters with dashes
Trav L

I just asked a relevant question today on SO regarding to generating slug, aka/ slugify a title.

When fetch a URL with slug, you can either create an action that takes both ID (and other required arguments) and slug in and simply ignore the slug.

public ActionResult Foobar(int id, string slug)
{
    //-- Do Something
}

Or more elegant, Use map route to ignore trialing string behind your URL and map to Foobar(int id).

Omar

One way to do this is the following on your string

 string cleanString = originalString.ToLower().Replace(" ", "-"); // ToLower() on the string thenreplaces spaces with hyphens
 cleanString = Regex.Replace(cleanString, @"[^a-zA-Z0-9\/_|+ -]", ""); // removes all non-alphanumerics/underscore/hyphens

Now you can pass the cleanString (for titles,names etc) into the ActoinLink/Url.Action parameters and it will work great.

The pattern was taken from http://snipplr.com/view/18414/string-to-clean-url-generator/

I'm not 100% on the Regex pattern, if some Regex hero can chime in and offer a better one that would be great. From testing the Regex, it doesn't match spaces, but this shouldn't be a problem because the first line replaces all spaces with hyphens.

Update:

To use this code, you need to setup your routes to accept extra parameters.

We'll use a blog article title as an example.

        routes.MapRoute(
            "",                                              // Route name
            "View/{ID}/{Title}",                           // URL with parameters
            new { controller = "Articles", action = "View"}  // Parameter defaults
        );

In your ASP.NET MVC views, you can then do the following:

  <%= Html.ActionLink("View Article", "View", "Articles", new { ID = article.ID, Title = Html.SanitizeTitle(article.Title) }, null) %>

In the previous example, I use SanitizeTitle as an HTML helper.

public static string SanitizeTitle(this HtmlHelper html, string originalString)
{
     string cleanString = originalString.ToLower().Replace(" ", "-"); // ToLower() on the string then replaces spaces with hyphens
     cleanString = Regex.Replace(cleanString, @"[^a-zA-Z0-9\/_|+ -]", ""); // removes all non-alphanumerics/underscore/hyphens
     return cleanString;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!