4

How to generate and pass a JavaScript variable from MVC Controller?

 2 years ago
source link: https://www.codesd.com/item/how-to-generate-and-pass-a-javascript-variable-from-mvc-controller.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to generate and pass a JavaScript variable from MVC Controller?

advertisements

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())
{

}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK