MVC路线.MapRoute问题 [英] MVC routes.MapRoute issues
问题描述
我的ID =国家\城市"
我在表格中使用以下ActionLink:
Hi,
I have id = "country\city"
I''m using below ActionLink in a table:
@Html.ActionLink("change", "changeCity", new { id = item.myCountyCity })
但是因为我的ID每次单击链接时都有2个用反斜杠分隔的部分,因此出现错误.为了解决该问题,我编写了以下自定义路线:
but because my id has 2 sections separated by backslash every time I click on the link it gives me error. To resolve the problem I wrote this custom route:
routes.MapRoute(
"CityCountyRoute",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", county = "", id = "" });
但这条路线仍然无法使用,并且我仍然收到相同的错误.
谢谢您预先提供的帮助.
Still this route is not working and I’m still receiving same error.
Thank you for your help in advance
推荐答案
您有多种选择可以解决此问题.其中一些是:
1."\"不是网址友好字符.因此,在html中使用字符串时(例如,在"target"属性中),您必须UrlEncode
您的字符串.因此,请更改以下
You have multiple options to deal with this. Some of them are:
1. "\" is not a url friendly character. So you will have toUrlEncode
your string when using it in html (for example in the "target" property). So changing the following
@Html.ActionLink("change", "changeCity", new { id = item.myCountyCity })
到
to
@Html.ActionLink("change", "changeCity", new { id = Server.UrlEncode(item.myCountyCity) })
在控制器上,在您的操作方法中,您将必须像"UrlDecode"一样. Server.UrlDecode(id).
2.您可以用"\"分隔输入,并为操作方法提供2个参数-国家和城市.所以你的动作方法看起来像是
On the controller, in your action method, you will have to "UrlDecode", like. Server.UrlDecode(id).
2. You can split your input by "\" and supply the action method with 2 parameters - country and city. So you action method would look like
public ActionResult Index(string country, string city)
{
return View();
}
然后您的路线将为
And then your route will be
routes.MapRoute(
"CityCountyRoute",
"{controller}/{action}/{country}/{city}",
new { controller = "Home", action = "Index", county = @"\s+", city = @"\s+" });
国家和城市为非空字符串.现在,您可以将Html.ActionLink调用为
where country and city are non-empty strings. Now you could have your Html.ActionLink call as
@Html.ActionLink("change", "changeCity", new { country = item.myCountyCity.Split('\\').First(), city = item.myCountyCity.Split('\\').Last() })
更好的方法是在控制器中执行此操作,并将这些值保存在传递给视图的模型中.因为视图中的代码量越少越好!
希望这会有所帮助!
Even better way would be do this would be to do this in the controller and have these values in a model which is passed to the view. Because the lesser the amount of code in your views, better it is!
Hope this helps!
这篇关于MVC路线.MapRoute问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!