Reputation: 823
I am trying to allow the user to edit names in an MVC application.
The controller function has this signature:
[Route("function/edit/{id:int}/{name}/{sortorder:int}")]
public ActionResult Edit(int id, string name, int sortorder)
{...}
I am calling it in Javascript like this:
window.location.href = "@Url.Action("Edit", "Function")" + "/" + id + "/" + name + "/" + order;
It all works fine, until the name contains '/' or the name ends with a '.' then i get a "The resource cannot be found." from the server. This makes perfect sense, since the '/' and '.' characters rightly confuses the routing...
But how should i do this?? I want to allow '/' and '.' in the names.
Upvotes: 4
Views: 4518
Reputation: 119076
You need to encode the data so characters such as /
are passed correctly. For this you should use the encodeURIComponent
function:
window.location.href =
"@Url.Action("Edit", "Function")" + "/" + id + "/" +
encodeURIComponent(name) + "/" + order;
For example, this is the difference before and after encoding:
var test = "this.is/a test";
alert(test);
alert(encodeURIComponent(test));
Additional to this, your MVC application is also having issues due to the way it decodes the URL. One solution to this is to reorder the parameters in your route to have the name
value last and give it a catch-all modifier:
[Route("function/edit/{id:int}/{sortorder:int}/{*name}")]
This forces MVC routing to pick up the last part as the entire value for name
.
Upvotes: 3