Write the model as an object available in Javascript
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(m开发者_如何学编程odel.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!
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);
});
精彩评论