0

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.

1
  • 1
    can you try this: var data = '@JsonConvert.SerializeObject(Model)'; var jsObj = JSON.parse(data.replace(/&quot;/g,'"')); Commented May 13, 2016 at 8:31

1 Answer 1

1

Assign the serialized Model to js variable.

var data = '@JsonConvert.SerializeObject(Model)';

When the Model is Serialized to Json, it contains &quot instead of " character. So replace it with ", parse it and assign to js variable.

var jsObj = JSON.parse(data.replace(/&quot;/g,'"'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.