Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 281
Aiju Avatar asked Aug 14 '14 09:08

Aiju


People also ask

How can get JSON data from Controller using Ajax in MVC?

Create target "JSON object Mapper" object class file according to the business requirements. Create a "Controllers\HomeController. cs" file with default Index method and GetData(...) method with string type input query parameters for Ajax call with following lines of code i.e.


3 Answers

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

}
like image 93
Igor Semin Avatar answered Oct 06 '22 19:10

Igor Semin


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

                }

            });
like image 36
Pranay Rana Avatar answered Oct 06 '22 18:10

Pranay Rana


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

}
like image 1
Aiju Avatar answered Oct 06 '22 19:10

Aiju