I'm trying to convert the C# Model in razor to javascript model using JsonConvert.SerializeObject.
var brandsCollectionModel = '@(Html.Raw(JsonConvert.SerializeObject(Model)))';
The Model contains a number of properties of a different type.
The problem is that some of these properties contain special characters, such as "".
Unfortunately this causes javascript syntax error:
"SyntaxError: Unexpected token
I'm trying to find a way to detect a property that contains special characters and encode it.
I'm using Html.Raw to prevent encoding as I don't want to escape double quotes that are generated when converting Model to JSON string.
I would be thankful for your help.
Talk1:
can you try this: var data = '@JsonConvert.SerializeObject(Model)'; var jsObj = JSON.parse(data.replace(/"/g,'"'));
Solutions1
Assign the serialized Model to js variable.
var data = '@JsonConvert.SerializeObject(Model)';
When the Model is Serialized to Json, it contains " instead of " character. So replace it with ", parse it and assign to js variable.
var jsObj = JSON.parse(data.replace(/"/g,'"'));