views:

989

answers:

3

I would like to develop URL's which look like the following:

http://mysite.com/products/1/best-product-in-the-world

Where all i need to get to the proper record is the following route:

http://mysite.com/products/1

When I add the product description piece to the URL ("best-product-in-the-world") I get URL encoding issues. I've tried to use Server.UrlEncode when constructing this portion of my URL in an ActionLink(...):

<%= Html.ActionLink(item.Subject, "../Post/Detail", 
    new { id = item.ID, 
          descriptiveUrl = Server.UrlEncode(Product.ShortDescription) }, 
    new { rel = "canonical", 
          title = Product.ShortDescription, 
          @class = "product-hyperlink" })%>

But this renders regularly encoded elements for special characters and spaces, much like the following:

http://localhost:2392/Products/Detail/1/best+product+in+the+world253f

...which creates a 400, bad request exception. Not sure I've done the question justice, but can provide further clarification if need be.

Update: this post's URL is as follows, and i'm trying to do something very similar!

http://stackoverflow.com/questions/1148955/creating-search-engine-friendly-urls-in-asp-net-mvc
+2  A: 

A simple option would be to add a property to your model object with an accessor that normalises the appropriate field (short description in this case) down to a suitable "slug"; that is, the bit of junk text after the identifier. You then use this when constructing the URI.

The normalisation process might be as simple as removing any non-alphanumeric characters and replacing spaces with hyphens.

Rob
I think you are correct. Here's another post which is asking the same question (http://stackoverflow.com/questions/217960/how-can-i-create-a-friendly-url-in-asp-net-mvc). I guess I want to make sure that I'm generating a URL-safe "slug".
jn29098
+1  A: 

The standard practice here is to store a 'slug' with each post that will function as the post's outward-facing URL. For example, your slug for the above post would be:

best-product-in-the-world

A decent CMS will do this for you automatically, and allow you to tweak the slug before saving.

James D
So I'm not using a CMS. Are you familiar with any libraries or snippets which handle all possible character variations and issues to generate the initial slug value?
jn29098
+2  A: 

In a deeper Google search, I found the following link for generating slugs:

http://www.intrepidstudios.com/blog/2009/2/10/function-to-generate-a-url-friendly-string.aspx

Thanks @Rob and @Coding the Wheel for giving me the terminology I really needed to find this answer!

jn29098