如何用 ASP.NET MVC 中的路由配置中的连字符替换 %20
How to replace %20 with a hyphen from routing config in ASP.NET MVC
我需要指导来移除我的 url 中的模数符号。我希望我的路由完全如下所示。
whosebug.com/questions/15881575/get-the-selected-value-of-a-dropdownlist-asp-net-mvc
我的路由returns某事
whosebug.com/questions/15881575/get%20the%20selected%20value%20of%20a%20dropdownlist-asp-net-mvc.
注意返回的 %20。请问我如何获得连字符?
下面是我的路由配置。
routes.MapRoute(
name: null,
url: "{controller}/{action}/{id}/{title}",
defaults: new
{
controller = "Home",
action = "Index",
title=UrlParameter.Optional,
id = UrlParameter.Optional
}
);
标题是我的操作方法中的一个字符串参数。我想这样做:
routes.MapRoute(
name: null,
url: "{controller}/{action}/{id}/{title}",
defaults: new
{
controller = "Home",
action = "Index",
title=UrlParameter.Optional.ToString().Replace(' ','-'),
id = UrlParameter.Optional
}
);
然而它失败了。我也试过
title=UrlParameter.Optional.ToString().Replace("%20","-"),
它也失败了。我对此很陌生,并试图让它变得更好。请提供任何帮助。
%20
是 space 的 URL 编码版本。您无法使用路由定义解决此问题,您必须首先修改生成 link 的代码,以便删除 spaces.
例如,如果您目前正在使用以下方式生成 link:
@Html.ActionLink(item.Title, "Details", new {
id = item.Id,
title = item.Title
})
您可以将其更改为
@Html.ActionLink(item.Title, "Details", new {
id = item.Id,
title = item.Title.Replace(" ", "-")
})
请注意,您可能需要处理 space 以外的其他字符,因此您最好使用:
title = Regex.Replace(item.Title, "[^A-Za-z0-9]", "")
我的偏好是将其变成 POST。然后你不写任何代码将任何东西转换成任何东西。
我需要指导来移除我的 url 中的模数符号。我希望我的路由完全如下所示。
whosebug.com/questions/15881575/get-the-selected-value-of-a-dropdownlist-asp-net-mvc
我的路由returns某事
whosebug.com/questions/15881575/get%20the%20selected%20value%20of%20a%20dropdownlist-asp-net-mvc.
注意返回的 %20。请问我如何获得连字符?
下面是我的路由配置。
routes.MapRoute(
name: null,
url: "{controller}/{action}/{id}/{title}",
defaults: new
{
controller = "Home",
action = "Index",
title=UrlParameter.Optional,
id = UrlParameter.Optional
}
);
标题是我的操作方法中的一个字符串参数。我想这样做:
routes.MapRoute(
name: null,
url: "{controller}/{action}/{id}/{title}",
defaults: new
{
controller = "Home",
action = "Index",
title=UrlParameter.Optional.ToString().Replace(' ','-'),
id = UrlParameter.Optional
}
);
然而它失败了。我也试过
title=UrlParameter.Optional.ToString().Replace("%20","-"),
它也失败了。我对此很陌生,并试图让它变得更好。请提供任何帮助。
%20
是 space 的 URL 编码版本。您无法使用路由定义解决此问题,您必须首先修改生成 link 的代码,以便删除 spaces.
例如,如果您目前正在使用以下方式生成 link:
@Html.ActionLink(item.Title, "Details", new {
id = item.Id,
title = item.Title
})
您可以将其更改为
@Html.ActionLink(item.Title, "Details", new {
id = item.Id,
title = item.Title.Replace(" ", "-")
})
请注意,您可能需要处理 space 以外的其他字符,因此您最好使用:
title = Regex.Replace(item.Title, "[^A-Za-z0-9]", "")
我的偏好是将其变成 POST。然后你不写任何代码将任何东西转换成任何东西。