Search code examples
javascriptasp.net-mvcasp.net-mvc-3

How to access item data in Javascript, if my Model is a QueryTable in MVC3?


I am new with MVC. I found this site is very helpful. But I've been struggling with the Model data accessing from Javascript. Here is my question.

I know if I controller return a single item, then I can use <%: Model.Name%> in <script> section.

But for the case where there are more items in Model, <%foreach (var item in Model) %> would not work in <script> even it works in other part of the view.

Can somebody shed me some light on this?

Also could somebody recommend a good book on MVC, and Razor?


Solution

  • It would be helpful to know more about your Model class. Most likely, you have a class with some kind of collection:

    public class CollegeCourse
    {
        public string Professor {get;set;};
        public List<Student> Students {get;set;};
    }
    

    You can loop through this collection in your server-side code like this:

    <% foreach (var student in Model.Students) %>
    

    As far as JavaScript... The example you gave is an example of how you would loop through your List<T> and build some HTML on the server side. But by the time your page loads in the browser, that model data is long gone.

    To interact with model data from JavaScript, you need to choose a strategy for getting the data to the browser. A few ideas:

    • Transform your data to JSON on when your page loads, then write it out in <script> tags.
    • Embed your data in HTML tags, perhaps by using data- attributes. Then you can use jQuery to retrieve the values.
    • Add an action to your controller that returns the data you need as JSON. Then, after your page loads, you can use a jQuery AJAX call to retrieve the model data and do whatever magic you plan to do with it.

    The first two options aren't really considered good practices. I'd recommend that you look into the AJAX approach. Here's a quick example that shows how you might be able to do this. It's not too difficult, and MVC3 even has some built-in helpers to make setting up the AJAX call simpler.

    If you're generally comforable with ASP.NET, then Professional ASP.NET MVC3 is an excellent book to get your head around MVC and Razor.