0

My model has one field that contains collection of items. I want to access that collection from a jquery from the view that is bound with this particular model.

how can I achieve this?

3
  • from a jquery? what do you mean exactly Commented Jan 5, 2013 at 20:03
  • I have written javascript functions in my MVC view under scripts section.. I want to access some properties of the model from this javascript or using $ function. Commented Jan 5, 2013 at 20:24
  • Model?? you mean a server side ViewModel? i.e C# or VB Class Commented Jan 5, 2013 at 21:05

2 Answers 2

2

Here is a slick way to do it. Build up a JSON data object via a foreach loop. Loading you data via an ajax call would be better, but that is a diferent solution for a different day.

Here I assume you have a collection of items that at least has an Id, and Name property. You will want to make your @foreach loop a little better than mine because JSON does not really allow the extra ',' at the end of the last item.

var data = [ @foreach (var item in Model.MyCollection) { <text>{"key":"@item.Id", "value":"@item.Name"},</text> } ]; $.each(data, function(i) { alert(data[i].key + ": " + data[i].value); }); 
Sign up to request clarification or add additional context in comments.

4 Comments

Oh, using Razor view engine in this example.
Thanks for the valuable reply. I think I am near to the solution. But I am getting $.data is undefined error, while my markup is as follow:
<div style="visibility:visible;"> var data = [ {"id":"1", "ui_bgcolor":"Green", "ui_forecolor": "Black"}, {"id":"2", "ui_bgcolor":"Amber", "ui_forecolor": "Black"}, {"id":"3", "ui_bgcolor":"Red", "ui_forecolor": "White"} ] </div> <script type="text/javascript"> function SetGradeDLLItemStyling() { $.each(data, function (i) { alert(data[i].UIBackgroundColor); }); } </script>
Needs to be in Script block. On my cell, might not be seeing your comment correctly.
0

I do something like this, not sure how 'correct' it is, but it works and makes sense to me.

var view = Backbone.View.extend({ el: $('window'), render: function() { var that = this; var model = new myModel(); model.fetch({ success: function({ that.dataModel = model; }); }); } }); 

And then anywhere you can do this.dataModel and it should be your model

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.