Nuru Salihu
Nuru Salihu

Reputation: 4928

How to replace %20 with a hyphen from routing config in ASP.NET MVC

I need guidance removing the Modulos signs from my url. I want my routing exactly like below.

stackoverflow.com/questions/15881575/get-the-selected-value-of-a-dropdownlist-asp-net-mvc

My routing returns something

stackoverflow.com/questions/15881575/get%20the%20selected%20value%20of%20a%20dropdownlist-asp-net-mvc.

Notice the %20 returned. Please how do I get a hyphen instead?

Below is my routing config.

  routes.MapRoute(
          name: null,
          url: "{controller}/{action}/{id}/{title}",
          defaults: new
          {
              controller = "Home",
              action = "Index",
              title=UrlParameter.Optional,
              id = UrlParameter.Optional
          }
          );

Title is a string parameter from my action method. I thought of doing like this:

routes.MapRoute(
          name: null,
          url: "{controller}/{action}/{id}/{title}",
          defaults: new
          {
              controller = "Home",
              action = "Index",
              title=UrlParameter.Optional.ToString().Replace(' ','-'),
              id = UrlParameter.Optional
          }
          );

However it fails. I alternatively tried

 title=UrlParameter.Optional.ToString().Replace("%20","-"),

It fails as well. I am new to this and trying to get it better. Please any help would be appreciated.

Upvotes: 1

Views: 2139

Answers (2)

Andy V
Andy V

Reputation: 1017

My preference would be to turn this into a POST. Then you don't write any code that converts anything to anything else.

Upvotes: 0

Richard
Richard

Reputation: 30618

%20 is the URL-encoded version of a space. You cannot solve this problem using the routing definitions, you must modify your code which generates the link in the first place, so that it strips out the spaces.

For example, if you are currently generating your link using:

@Html.ActionLink(item.Title, "Details", new { 
    id = item.Id, 
    title = item.Title 
})

You would change it to

@Html.ActionLink(item.Title, "Details", new {
    id = item.Id,
    title = item.Title.Replace(" ", "-")
})

Note that you'll probably need to deal with other characters besides space, so you are probably better off using:

title = Regex.Replace(item.Title, "[^A-Za-z0-9]", "")

Upvotes: 6

Related Questions