Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 URL Encoding?

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:

  1. Should I expect it to automatically url encode values? Is there any way to set that up?
  2. 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!

like image 762
Alpha Avatar asked Jul 18 '11 00:07

Alpha


2 Answers

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.

like image 162
Darin Dimitrov Avatar answered Sep 28 '22 05:09

Darin Dimitrov


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");
}
like image 36
David Silva Smith Avatar answered Sep 28 '22 05:09

David Silva Smith