开发者

Write the model as an object available in Javascript

开发者 https://www.devze.com 2023-02-04 19:36 出处:网络
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.

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);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消