MVC3 URL Encoding?

ASP.NET MVC3 / Razor.

I found that when I create a link for an action, let's say like this:

@Html.ActionLink(product.Title, "Detail", "Products", new { id = product.ProductID }, null) 

The MVC3 engine creates my product link. For instance:

 http://myhost/{ActionUrl}/PRODID 

However, if my product identifier must contain any special character, it will not be URL encoded.

 http://myhost/{ActionUrl}/PROD/ID 

Of course, this violates my routing. My questions:

  • Should I expect it to automatically encode url values? Is there any way to fix this?
  • If not, what is the cleanest way to encode and decode them? I really do not want to do this in every controller.

Thanks!

+6
source share
2 answers

If your identifier contains special characters, I would recommend that you pass it as a query string, and not as part of the path. If you do not get ready for the bumpy road. Place an order after a blog post .

+4
source

I did not get this to work along the way, but to make this work with the QueryString parameter, as @Darin noted, here is the code:

 @Html.ActionLink(product.Title, "Detail", "Products", new { id = product.ProductID }, "") 

created actionLink as a request for me as follows: Products/Detail?id=PRODUCTID

my route at 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"); } 
+1
source

Source: https://habr.com/ru/post/892961/


All Articles