开发者

Pass List<objects> to the jQuery function

I want to pass the List to my jquery function in asp.net mvc application, and want to itterate it in jquery function. what i have to do.

Edited: Added my code here

Scrip开发者_开发技巧t:

 $.getJSON('/LoadTest/GetAllQuestionsForTest', function(data) {
            $.each(data, function() {

                    alert("hi");
                });
            });

controller:

[AcceptVerbs(HttpVerbs.Get)]
        public JsonResult GetAllQuestionsForTest()
        {
            int testId = 1;
            int id = Convert.ToInt32(testId);
            List<Question> questionList;

            questionList = questionManager.GetquestionsByTestId(id);
            return Json(questionList,JsonRequestBehavior.AllowGet);
        }


You could serialize your list to a JSON object and then loop through it:

<script type="text/javascript">
    var list = <%= new JavaScriptSerializer().Serialize(Model.YourList) %>;
    $.each(list, function(index, element) {
        // TODO: Do something with the element.
    });
</script>

Another possibility is to fetch this list in an AJAX request:

<script type="text/javascript">
    $.getJSON('<%= Url.Action("GetMyList") %>', function(result) {
        $.each(result, function(index, element) {
            // TODO: Do something with the element.
        });
    });
</script>


You can return a JsonResult from your MVC action.

List<MyObject> myList = /* get the data */

return Json(myList);

This assumes that you're object will serialise nicely without any complications. If the object is complex you may want to serialize it yourself with a JavaScriptSerializer and return a Content action result.

Another serialiser you may want to look at would be json.net


jQuery is Javascript in the end, it can't understand CLR types and so many formats can be applied on your data (Objects at hand) like serializing them to JSON so the jQuery at the client side can understand it.

for JSON, HERE is this so beneficial website to validate your JSON notation to make sure it is valid and represented correctly.


In your MVC application, you can result a JsonResult:

public JsonResult MyAction()
{
    var myList = GetMyList();
    return Json(myList);
}

Then in jQuery, you can call your controller as an AJAX request and iterate though them:

$.getJSON('/Controller/MyAction',function(data){
   $.each(data, function(){
        console.log(this);
   });
});

Example: http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/


You can return a JsonResult from the action method like :

return new JsonResult{Data= lstObjects}; // lstObjects is the collection/list of objects.

And then to iterate you can take help of $.each(...) function or noraml for{}.. loop. But $.each(...) will give you better performance over large collections.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜