简体   繁体   English

如何在ASP.NET MVC中使用路由配置中的连字符替换%20

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

I need guidance removing the Modulos signs from my url. 我需要从我的网址中删除Modulos标志的指南。 I want my routing exactly like below. 我希望我的路由完全如下所示。

stackoverflow.com/questions/15881575/get-the-selected-value-of-a-dropdownlist-asp-net-mvc stackoverflow.com/questions/15881575/获取所选下拉列表的值-asp-net-mvc

My routing returns something 我的路线返回了一些东西

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

Notice the %20 returned. 请注意,返回了%20。 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. 请任何帮助将不胜感激。

%20 is the URL-encoded version of a space. %20是空格的URL编码版本。 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]", "")

My preference would be to turn this into a POST. 我的偏好是将其转换为POST。 Then you don't write any code that converts anything to anything else. 然后,您无需编写任何将任何内容转换为其他任何内容的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM