1

first time using Asp.Net MVC here.
I have a model class defined with 3 properties and I would like to access this model from javascript code on the view.

The best I found was this page It would allow me to do something like this:

<script>
 var model = <%= Model.ToJson() %>
 alert(model.Prop1);
</script>

Since this code is based on an article from 2007 I was wondering if there is a better way to do this.

Thanks!

2
  • I'd suspect that if there were anything seriously wrong with this approach then you'd have found lots of alternatives out there. I think the actuality is that most people don't find the need to push the entire Model down to the client javascript, I'm not sure I can think of a reason that I'd want to do that to be honest. What's driving your investigation here, it'd be interesting to learn your objective. Commented Jan 16, 2011 at 16:48
  • The data of my page will be updated with ajax regularly with timed requests from JSON, but I thought that I could render the initial data with Javascript by having the JSON as a var on the page directly, this way it won't need to wait for a AJAX callback to start filling the page. Commented Jan 18, 2011 at 8:09

1 Answer 1

2

Yes, that's a very good way to achieve this. It uses JavaScriptSerializer to serialize your model into a JSON object and ensure proper escaping.

As an alternative if you are using AJAX you could directly have a controller action returning JSON:

public ActionResult Foo()
{
    var model = FetchTheModel();
    return Json(model, JsonRequestBehavior.AllowGet);
}

and then using jquery consume this action:

$.getJSON('<%= Html.Action("Foo") %>', function(result) {
    alert(result.Prop1);
});
Sign up to request clarification or add additional context in comments.

6 Comments

Any reason for the downvote? Please leave a comment when downvoting.
I didn't downvote, but afaik JavascriptSerializer is depricated, and you should use DataContractSerializer instead... I am not a c# guru tho
@Martin, JavaScriptSerializer is not deprecated. I don't know where did you read this. The just released ASP.NET MVC 3 framework uses it to generate JSON. In fact it was temporally deprecated in .NET 3.5 and undepretaced back in .NET 3.5 SP1. It's usage is perfectly fine.
It was deprecated at some point,. but seems to have been undeprecated again in .NET 3.5SP1.. try to google for "javascriptserializer deprecated" and you will get many results :)
Darin, a good answer. You are doing a great answers most of the time. Do not take this downvote into account. I upvoted your answer :-).
|

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.