Reputation: 19664
I have an action that takes 2 strings. One of the strings is a big, ugly json string. I suspect that the action will not allow the special characters to be passed because I keep getting a 400 - Bad Request.
Can a serialized json object be passed to an action?
public ActionResult SaveState(string file, string state)
{
string filePath = GetDpFilePath(file);
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.Load(filePath);
HtmlNode stateScriptNode =
htmlDocument.DocumentNode.SelectSingleNode("/html/head/script[@id ='applicationState']");
stateScriptNode.InnerHtml = "var applicationStateJSON =" + state;
htmlDocument.Save(filePath);
return null;
}
ClientScript
'e' is a large json string
$.post('/State/SaveState/' + fileName+'/' + '/' + e + '/');
strong text
I am now encoding the text using UriEncoding() but it makes no difference. I don't think that MVC Actions allow me to send these special characters by default.. is that true? How do you work around this?
$.post('/State/SaveState/' + encodeURIComponent(fileName) + '/' + '/' + encodeURIComponent(e) + '/');
Sample request:
Request URL:http://localhost:51825/State/SaveState/aa6282.html//%7B%22uid%22%3A%22testUser%22%2C%22a
Upvotes: 2
Views: 807
Reputation: 19664
Because I am send this data to the sever and the size of the string I am sending is large. I really should be sending the data in the post body.
It seems that there is also a limitation on the amount of data that you can send via the query string. I cannot be certain that this was the source of the error message but it certainly would make sense. In case the following post works correctly:
$.post('/State/SaveState/', { file: fileName, state: e });
Upvotes: 1
Reputation: 1576
You need to encode it when the request is made:
$.post('/State/SaveState/' + encodeURIComponent(fileName) + '/' + encodeURIComponent(e));
Upvotes: 2
Reputation: 7947
Yes, serialized JSON object can be passed to an action method. MVC3 makes this even easier with built-in JSON binding. I use the json2 library to serialize the objects. See this post for more details. Works really great.
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx
Upvotes: 1
Reputation: 32576
You probably need to HTML-encode e
before you add it to the URL. Also, you have an extra /
that you don't need.
Upvotes: 0