How to get a list from mvc controller to view using jquery ajax

80,624

Solution 1

Why you use HttpPost for GET-method? And need return JsonResult.

public class FoodController : Controller
{

    public JsonResult getFoodDetails(int userId)
    {
        IList<Food> FoodList = new List<Food>();

        FoodList = FoodService.getFoodDetails(userId);

        return Json (new{ FoodList = FoodList }, JsonRequestBehavior.AllowGet);
    }
}


function GetFoodDetails() {
    debugger;
    $.ajax({
        type: "GET",
        url: "Food/getFoodDetails",
        data: { userId: Id },
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (result) {
            debugger;
            alert(result)
        },
        error: function (response) {
            debugger;
            alert('eror');
        }
    });

}

Solution 2

you can do like this , return json data and print it

Read full tutorial : http://www.c-sharpcorner.com/UploadFile/3d39b4/rendering-a-partial-view-and-json-data-using-ajax-in-Asp-Net/

public JsonResult BooksByPublisherId(int id)
{
      IEnumerable<BookModel> modelList = new List<BookModel>();
      using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
      {
            var books = context.BOOKs.Where(x => x.PublisherId == id).ToList();
            modelList = books.Select(x =>
                        new BookModel()
                        {
                                   Title = x.Title,
                                   Author = x.Auther,
                                   Year = x.Year,
                                    Price = x.Price
                          });
            }
    return Json(modelList,JsonRequestBehavior.AllowGet);

        }

javascript

$.ajax({

                cache: false,

                type: "GET",

                url: "@(Url.RouteUrl("BooksByPublisherId"))",

                data: { "id": id },

                success: function (data) {

                    var result = "";

                    booksDiv.html('');

                    $.each(data, function (id, book) {

                        result += '<b>Title : </b>' + book.Title + '<br/>' +

                                    '<b> Author :</b>' + book.Author + '<br/>' +

                                     '<b> Year :</b>' + book.Year + '<br/>' +

                                      '<b> Price :</b>' + book.Price + '<hr/>';

                    });

                    booksDiv.html(result);

                },

                error: function (xhr, ajaxOptions, thrownError) {

                    alert('Failed to retrieve books.');

                }

            });

Solution 3

The reason why i am not getting the result was.. I forgot to add json2.js in the library

 public class FoodController : Controller
    {
       [System.Web.Mvc.HttpGet]
        public JsonResult getFoodDetails(int userId)
        {
            IList<Food> FoodList = new List<Food>();

            FoodList = FoodService.getFoodDetails(userId);

            return Json (FoodList, JsonRequestBehavior.AllowGet);
        }
    }

function GetFoodDetails() {
    debugger;
    $.ajax({
        type: "GET",
        url: "Food/getFoodDetails",
        data: { userId: Id },
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (result) {
            debugger;
            alert(result)
        },
        error: function (response) {
            debugger;
            alert('eror');
        }
    });

}
Share:
80,624
Aiju
Author by

Aiju

Updated on July 18, 2020

Comments

  • Aiju
    Aiju almost 4 years

    I need to get a list from mvc controller to view using jquery ajax. how can i do that. this is my code. Its alerting error message.

    In Controller

     public class FoodController : Controller
        {
           [System.Web.Mvc.HttpPost]
            public IList<Food> getFoodDetails(int userId)
            {
                IList<Food> FoodList = new List<Food>();
    
                    FoodList = FoodService.getFoodDetails(userId);
    
                    return (FoodList);
            }
        }
    

    In view

    function GetFoodDetails() {
            debugger;
            $.ajax({
                type: "POST",
                url: "Food/getFoodDetails",
                data: '{userId:"' + Id + '"}',
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    debugger;
                    alert(result)
                },
                error: function (response) {
                    debugger;
                    alert('eror');
                }
            });
    
        }
    

    enter image description here

    • markpsmith
      markpsmith almost 10 years
      Change the method return type to ActionResult, and return your list as return Json(new { MyList = FodList}, JsonRequestBehavior.AllowGet);
    • Kartikeya Khosla
      Kartikeya Khosla almost 10 years
      problem solved....???
  • Aiju
    Aiju almost 10 years
    Sorry it is not working!! Its getting into error part.
  • Kartikeya Khosla
    Kartikeya Khosla almost 10 years
    just see updated answer it will work..@AijuThomasKurian
  • Aiju
    Aiju almost 10 years
    do i have to change any thing in routesconfig?
  • Kartikeya Khosla
    Kartikeya Khosla almost 10 years
    just check because in your action... public JsonResult getFoodDetails(int userId)...if userid from ajax is null or empty... then it will create problem or just use "?" with int as i have used in my answer...@AijuThomasKurian
  • Aiju
    Aiju almost 10 years
    Every thing is working fine till the return part. I have a list with some data. Only thing is how pass that data to view? The call is going to db and i am getting the result as a list.
  • Kartikeya Khosla
    Kartikeya Khosla almost 10 years
    @AijuThomasKurian...just apply breakpoint below "Flist" according to my answer and see it has proper list or not???
  • Kartikeya Khosla
    Kartikeya Khosla almost 10 years
    try using $.getJSON instead of ajax ..just see updated answer..@AijuThomasKurian
  • AuroMetal
    AuroMetal about 8 years
    This solution worked absolutely fantastic for me. When I presented this solution to the lead developer he asked me "Why JsonRequestBehavior.AllowGet?". Well sorry, no idea, I said. He suggested me to research to get an understand about it and voilà much clear now: stackoverflow.com/a/8464685/3812244
  • Igor Semin
    Igor Semin about 6 years
    @IMAK, why not? It anyway will be serialized to array in json object.