Dowemo
0 0 0 0


Question:

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


Best Answer:


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.');
                }
            });



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs