Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have id = “country\city”
I'm using below ActionLink in a table:

C#
@Html.ActionLink("change", "changeCity", new { id = item.myCountyCity })

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:

C#
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
Posted
Updated 24-Jun-12 15:45pm
v2

1 solution

You have multiple options to deal with this. Some of them are:

1. "\" is not a url friendly character. So you will have to UrlEncode your string when using it in html (for example in the "target" property). So changing the following

C#
@Html.ActionLink("change", "changeCity", new { id = item.myCountyCity })


to

C#
@Html.ActionLink("change", "changeCity", new { id = Server.UrlEncode(item.myCountyCity) })


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

C#
public ActionResult Index(string country, string city)
{
   return View();
}


And then your route will be

C#
routes.MapRoute(
"CityCountyRoute",
"{controller}/{action}/{country}/{city}",
new { controller = "Home", action = "Index", county = @"\s+", city = @"\s+" });

where country and city are non-empty strings. Now you could have your Html.ActionLink call as

C#
@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!
 
Share this answer
 
v2
Comments
Sandeep Mewara 25-Jun-12 13:01pm    
5!
Karthik. A 25-Jun-12 13:42pm    
Thanks Sandeep!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900