I have an AJAX call to an MVC controller that is sending a JSON string with left and right square brackets in some of the keys, like this:
"Styles": [{
"Id": 1,
"Name": "background-color",
"Value": "#036",
"Selector": "input[type=text]:hover,input[type=password]:hover"
}]
When the controller tries to parse the JSON, it breaks on the brackets:
The key is invalid JQuery syntax because it is missing a closing bracket.
Parameter name: key
Is there a way I can send these strings through with the brackets intact or is there a better approach?
EDIT:
This fails before it even hits a debugger in my controller. The method that tries to parse it is System.Web.Mvc.NameValueCollectionValueProvider.NormalizeJQueryToMvc. Here is what that method is doing:
internal static string NormalizeJQueryToMvc(string key)
{
if (key == null)
{
return string.Empty;
}
StringBuilder sb = new StringBuilder();
int i = 0;
while (true)
{
int indexOpen = key.IndexOf('[', i);
if (indexOpen < 0)
{
sb.Append(key, i, key.Length - i);
break; // no more brackets
}
sb.Append(key, i, indexOpen - i); // everything up to "["
// Find closing bracket.
int indexClose = key.IndexOf(']', indexOpen);
if (indexClose == -1)
{
throw Error.Argument("key", SRResources.JQuerySyntaxMissingClosingBracket);
}
if (indexClose == indexOpen + 1)
{
// Empty bracket. Signifies array. Just remove.
}
else
{
if (char.IsDigit(key[indexOpen + 1]))
{
// array index. Leave unchanged.
sb.Append(key, indexOpen, indexClose - indexOpen + 1);
}
else
{
// Field name. Convert to dot notation.
sb.Append('.');
sb.Append(key, indexOpen + 1, indexClose - indexOpen - 1);
}
}
i = indexClose + 1;
if (i >= key.Length)
{
break; // end of string
}
}
return sb.ToString();
}