Abhishek Jadhav
Abhishek Jadhav

Reputation: 129

Unable to fetch model objects list returned by action using ajax call in mvc view

Controller Action:

        [HttpGet]
        public JsonResult CriteriasForAward(int awardId)
        {
            var criteriaList = _awardService.GetCriteriasForAward(awardId);
            return Json(new { data = criteriaList }, JsonRequestBehavior.AllowGet);
        }

Ajax Call:

<script>
    jQuery(document).ready(function () {
          $("#Award").change(function () {
              var selectdAward = $("#Award").val();
            alert("Id" + selectdAward);
            var ServiceUrl = "/Nomination/CriteriasForAward?awardId=" + selectdAward;

            $.ajax({
                type: 'GET',
                url: ServiceUrl,
                contentType: "application/json; charset=utf-8",
                error: function (xhr, err) {
                    alert(xhr.responseText)
                },
                success: function (data)
                {
                    debugger;

                $.each(data, function (key, val) {
                    alert(key);
                });


                }
            });
        });
    });



</script>

All the things are going good..Also ajax call is succeeded,the data field contain array of all objects returned by ajax but when i wanted to alert key of each item for testing then it alerts undefined for only once.. If i debug it in browser then it contains values as shown in snapshotenter image description here

Upvotes: 0

Views: 498

Answers (2)

SᴇM
SᴇM

Reputation: 7213

Try this:

 $.ajax({
     type: 'GET',
     url: ServiceUrl,
     contentType: "application/json; charset=utf-8",
     error: function (xhr, err) {
         alert(xhr.responseText)
     },
     success: function (data)
     {
         debugger;
         $.each(data.data, function (key, val) {
             alert(key);
         });
     }
 });

by Json(new { data = criteriaList }); you creating new Json object that have data property. So if you want to access to that, just add .data: data.data, or change the json property name, to make more readable.

Upvotes: 1

Deepak saini
Deepak saini

Reputation: 4270

In your response data is object so you have to call just like that

$.each(data.data, function (key, val) {
   alert(key);
});

There is another way to achieve this you have to send json_encode from controller.

Upvotes: 0

Related Questions