English 中文(简体)
How to generate and transmit a JavaScript variable from MVC Controller?
原标题:

I m trying to fill a JSON object with a list of items from the database when the page first loads. This list of items comes from the database. Right now, I ve strongly typed the View and am looping through the list of items to build an HTML unordered list, and then in the JavaScript building the JSON object from what s been output in the HTML. But this is clunky.

Ideally, I d like to take that data from the database in the Controller, fill an object (or variable), and send that variable over to the JavaScript to use there, and skip the HTML in between (the HTML will be updated dynamically using jQuery). The variable that arrives in the JavaScript doesn t have to be a JSON object, but it does need to hold information that I ve populated from the Controller. From there, I can build the JSON object in the JavaScript.

A friend told me this is possible and he currently uses this method, but has never tried it in ASP.NET MVC. Any ideas?

CLARIFICATION: I should have been more clear in my original question, but I am trying to send the variable/JSON over to an external javascript file, rather than handle the JSON object/create it inline within tags.

最佳回答

In your controller just

return Json(yourObject);

instead of

return View(yourObject);

the MVC framework will serialize almost anything into JSON, just watch out for linq-to-sql objects that have a circular relation.

If you then call this with jQuery ajax you will get a JSON object in "data".

If you want your controller to be able to return both html(view) or json you can check if the request is an ajax request like so:

if(Request.IsAjaxRequest())
{

}
问题回答

You can assign JSON directly to a [javascript] variable as it is valid javascript.

.NET includes a serializer in

System.Web.Script.Serialization.JavaScriptSerializer

In your controller you probably have something like a list that you are passing in:

ViewData["MyData"] = new List<int>() { 1, 2, 3 };

Then you could parse it inside the view with:

var serializer = new JavaScriptSerializer();
string data = serializer.Serialize(ViewData["MyData"]);
// data will be [1,2,3] I think
// objects with members will have data like { "MyVariable": "MyValue", ...}

You could also store an variable in the global scope and push() values onto it as you loop.

var MyData = new Array();

MyData.push(1);
MyData.push(2);
MyData.push(3);

This is how Flicker tackled this problem rather recently:

http://code.flickr.com/blog/2009/03/18/building-fast-client-side-searches/

The fastest way to do this, according to their observations, is to send the data as delimited text and then use String.prototype.split() to get the job done rather than a JSON parser.

Since we had already discovered that some methods of string manipulation didn’t perform well on large strings, we restricted ourselves to a method that we knew to be fast: split(). We used control characters to delimit each contact, and a different control character to delimit the fields within each contact. This allowed us to parse the string into contact objects with one split, then loop through that array and split again on each string.

Others have commented on various ways to turn your data into JSON. If you want your external JS file to have this JSON data, then you ll need to route requests for that JS file appropriately so that it is served as a dynamic request rather than one for a static file. Once you do so, you can dynamically generate the JSON part of the external JS file.

Yep. Find a JSON serializer for the language you re using from here: http://www.json.org/

Then once you ve instantiated and populated your data objects, you should be able to invoke a .toJSONString() method (or similar) which will spit out the JSON for transmission to the client.

You could just render some JavaScript instead of the unordered list in the HTML. So if you wanted to be able to access a list of JSON objects then something like

<html>
<body>
  <div>...</div>

  <script type="text/javascript">
    var list = {
      <% foreach(var item in Model) { %>
        { x:<%= item.X %>, Y:<%= item.Y %>, Z:<%= item.Z %> },
      <% } %>
    };
    // or
    var x = <%= Model.MySerializedJson %>
  </script>
</body>
</html>

Or you could use an Ajax call after the page has been rendered.





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签