For some reason, when I have a special character in my knockout model and convert it to a json object, the string ends where the special character is supposed to be and I get an error when deserializing it:
$.ajax({
url: "/Admin/Forms/Convert",
type: "post",
//contentType: "application/json",
dataType: "text",
data: "modelData=" + ko.toJSON(theModel),
success: function (data) {
// window.open("/Admin/Forms/DisplayClient");
var win = getFullWindow('/Admin/Forms/DisplayClient');
win.open();
},
error: function (xhr, status, msg) { alert(msg); }
});
When I get to this method:
public void Convert(string modelData)
{
Form form = JsonConvert.DeserializeObject<Form>(modelData);
}
I get an error:
Unterminated string. Expected delimiter: ". Path 'Name', line 1, position 178.
If a JSON string contains special characters like double quotes "
, backslashes \
or slashes /
, they need to be escaped with backslashes \
. There is no JSON parser that will be able to deal with a JSON string that isn't properly formatted in the first place.
So you need to make sure that your theModel
is formatted appropriately and according to JSON.org standards.
I have got the same error a few times. I have updated my web.config with greater max lengths to ensure no truncating.
<httpRuntime maxQueryStringLength="2097151" maxUrlLength="2097151" />
<security>
<requestFiltering>
<requestLimits maxQueryString="2097151" maxUrl="2097151" />
</requestFiltering>
</security>
The encodeURIComponent() function encodes a URI component.
This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #
This has now been added to my ajax requests:
$.ajax("URL", {
type: "POST",
cache: false,
data: { a: encodeURIComponent(jsonData), b: userID }
})
I found an answer to my own question: escape(ko.toJSON(theModel)) All I need is the escape function and it works great.