0

I'm serializing my model:

<script type="text/javascript">

    var Model = '@Model.ToJson()';

</script>

the ToJson is an extension method:

public static string ToJson(this object obj)
{
    var serializer = new JavaScriptSerializer();
    var val = serializer.Serialize(obj);
    return val;
}

Now I want to access my model in other javascript files by doing:

var hello = Model.id;

The problem is that it doesn't serialize correctly when I use '@Model.ToJson()' because of the quotes.

The serialized object looks like this:

var Model = "{ "id": "2231f87c-a62c-4c2c-8f5d-b76d11942301" }";

But in order for me to access id by Model.id it should look like this:

var Model = { "id": "2231f87c-a62c-4c2c-8f5d-b76d11942301" };

How can I enter razor syntax without quotes? Using asp.net syntax I think it's:

var Model = <%=Model.ToJson() %>

How do I do the same with razor? Thanks!

1
  • you surround @Model.ToJson() call with quotes... Note that you have mismatch between your sample ('@Model.ToJson()' and "object looks like" statement var Model = "{ "id": - notice different quote), so you may be running some other code at all... Commented Sep 12, 2013 at 18:11

2 Answers 2

1

If you use this JSON plugin you can do it all on the client and simply things. If you push up a JSON string, in javascript you could then do:

<script type="text/javascript">

    var Model = JSON.parse("@Model.JsonString");

</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Since Razor by default escapes out the quotes, you need to use Html.Raw:

var Model = @Html.Raw(Model.ToJson());

It will turn that into:

var Model = {"id":"whatever"};

which is valid javascript.

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.