2

I want to iterate through table data and poupulate links in a table.

Each row in the table has links of a similar fashion with several different ids interspersed. I'd like to use the Url factory to generate a template for the url route.

eg.

var urlHelper = new UrlHelper(HttpContext.Current.Request...);

 //code is a bit handwavy and may not compile
 var routeValues = new Dictonary<string,object>();
 routeData["action"] =  "myAction";
 routeData["controller"] =  "myAction";
 routeData["id1"] =  "{0}";
 routeData["id1"] =  "{2}";

 urlHelper.RouteUrl(routeValues);

MSDN REF UrlHelper.RouteUrl http://msdn.microsoft.com/en-us/library/dd505226(v=vs.118).aspx

I think when I currently use placeholders, it encodes the "{" signs and I havent really worked around it. I have seen a "{" in our project urls, so I would like to avoid decoding these charchters.

I'd also strongly prefer to avoid the solution of putting in myId1 = -9999, myId=-9999, myString='-9999', although this is an acceptable solution should it be nessecary.

Is there a good solution to generate routes with placeholders?

4

1 回答 1

0

Those are special characters that have to be Url encoded, so the Url Helper methods will always encode those characters. A work around could be to Url decode the generated url with placeholders. Then you need to make any replacements, manually url encoding the values yourself!

Generate the url template like this (Or with any other UrlHelper method instead of Url.RouteUrl):

var routeValues = new RouteValueDictionary();
routeValues["action"] = "myAction";
routeValues["controller"] = "myAction";
routeValues["id1"] = "{0}";

var urlTemplate = HttpUtility.UrlDecode(Url.RouteUrl(routeValues));

This would generate (with the default routes in MVC) the url template /myAction/myAction?id1={0}. Then when replacing the placeholders, you will need to url encode the string values yourself:

String.Format(urlTemplate, HttpUtility.UrlEncode("123"))

Which would generate /myAction/myAction?id1=123.

I would be careful with this approach, as you will need to manually convert values to strings and encode them. This also assumes that values hardcoded in your url template like myAction are safe and don't need to be url encoded (as we are decoding the generated url).

于 2014-08-21T09:18:07.653 回答