ASP.NET MVC3/Razor.
I found that when I create an action link, say, like this:
@Html.ActionLink(product.Title, "Detail", "Products", new { id = product.ProductID }, null)
The MVC3 engine creates my product link. For example:
http://myhost/{ActionUrl}/PRODID
However, if my product ID was to contain any special character, it wouldn't be URL encoded.
http://myhost/{ActionUrl}/PROD/ID
Of course, this breaks my routing. My questions are:
- Should I expect it to automatically url encode values? Is there any way to set that up?
- If not, then what is the most cleaner way to encode and decode those? I really do not want to do that in every controller.
Thanks!
2 Answers 2
If your id contains special characters I would recommend you passing it as a query string and not as part of the path. If not be prepared for a bumpy road. Checkout the following blog post.
-
It took me a while to realize, but you're totally right on your answer. Certain characters are like reserved keywords and you just can't do anything about it. For some others, you can do weird things or even use catch-all routes, but some of the special characters just will have to stay in that way (unless you want to do some rewriting with regexes).Alpha– Alpha07/21/2011 21:14:08Commented Jul 21, 2011 at 21:14
I didn't get this to work in the path, but to make this work as a QueryString parameter as @Darin pointed out here is the code:
@Html.ActionLink(product.Title, "Detail", "Products", new { id = product.ProductID }, "")
created the actionLink as a querystring for me like this: Products/Detail?id=PRODUCTID
my route in Global.asax.cs looked like this:
routes.MapRoute(
"ProductDetail",
"Products/Detail",
new { controller = "Products", action = "Detail" }
);
In my ProductController:
public ActionResult Detail(string id)
{
string identifier = HttpUtility.HtmlDecode(id);
Store.GetDetails(identifier);
return RedirectToAction("Index", "Home");
}
-
What happens when "PRODUCTID" contains "/" or "#"? What does the controller receive?Alpha– Alpha12/22/2011 15:03:51Commented Dec 22, 2011 at 15:03
-
the controller receives the / encoded as %2f. the HttpUtility.HtmlDecode will convert it back to a slash. I don't have code setup to test the # but I expect the controller will receive %23David Silva Smith– David Silva Smith12/22/2011 17:44:31Commented Dec 22, 2011 at 17:44
-
Thanks, it does make sense. I saw that you also moved it to the query string, but I am working with it on the path section. Even when encoding, it will break the path formation. I was looking for a way of handling that in the path. Thanks!Alpha– Alpha12/22/2011 20:15:11Commented Dec 22, 2011 at 20:15
-
Oops, I got caught up in the above answer and was still in that context.David Silva Smith– David Silva Smith12/22/2011 20:44:34Commented Dec 22, 2011 at 20:44
Explore related questions
See similar questions with these tags.