-3

I am facing a issue in my current project where I want to display custom URl for my pages. I have tried lot of techniques but none of them fulfills my requirement. I want URL like this:

http://www.anyDomain.com/What-Is-Your-Name

Currently, I am able to set the URL like this:

http://www.anyDomain.com/What-Is-Your-Name?Id=1

I want to ignore Querystring from URL. So that Controller can identify the request & respond accordingly.

Here, Id is used to fetch details from Database. How can I pass the Parameter Value from View to Controller so It can identify the request without adding it in URL?

My Controller

[Route("~/{CategoryName}")]
public ActionResult PropertyDetails(int Id)
{
}

RouteConfig

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults:
    new
    {
        controller = "Home",
        action = "Index",

    }
);

My View

<a href="@Url.Action("PropertyDetails", "Home", new {@Id=item.ID,@CategoryName = Item.Title })">

I just Noticed, I want URL like StackOverflow is using

http://stackoverflow.com/questions/43774917/wordpress-blog-type-permalink-in-mvccustom-url-routing
user692942
  • 16,398
  • 7
  • 76
  • 175
Harjeet Singh
  • 388
  • 2
  • 6
  • 22

1 Answers1

3

Using attribute routing to include the id and a title, the controller can look like this

public class HomeController : Controller {
    [HttpGet]
    [Route("{id:int}/{*slug}")] //Matches GET 43774917/wordpress-blog-type-permalink-in-mvccustom-url-routing
    public ActionResult PropertyDetails(int id, string slug = null) {
        //...code removed for brevity
    }

    //...other actions
}

This will match routes similar to what you observed with what StackOverflow is using.

In the view when generating your urls you can take advantage of the models to generate the format you wanted.

<a href="@Url.Action("PropertyDetails", "Home", new { @id=item.ID, @slug = item.Title.ToUrlSlug() })">

The ToUrlSlug() can be an extension method to convert the model Title to your desired format word-word-word

public static class UrlSlugExtension {

    public static string ToUrlSlug(this string value) {
        if (string.IsNullOrWhiteSpace(value)) return string.Empty;
        //this can still be improved to remove invalid URL characters
        var tokens = value.Trim().Split(new char[] {  ' ', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);

        return string.Join("-", tokens).ToLower();
    }
}

Found an answer here on how to generate the slug

How does Stack Overflow generate its SEO-friendly URLs?

With that, the custom URL would look something like

http://www.yourdomain.com/123456/what-is-your-name

for an item with an ID of 123456 and a title of "What Is Your Name"

Community
  • 1
  • 1
Nkosi
  • 235,767
  • 35
  • 427
  • 472