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

前端 未结 6 1913
孤街浪徒
孤街浪徒 2021-02-04 08:02

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

 publ         


        
6条回答
  •  抹茶落季
    2021-02-04 08:27

    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 modelList = new List();
          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 += 'Title : ' + book.Title + '
    ' + ' Author :' + book.Author + '
    ' + ' Year :' + book.Year + '
    ' + ' Price :' + book.Price + '
    '; }); booksDiv.html(result); }, error: function (xhr, ajaxOptions, thrownError) { alert('Failed to retrieve books.'); } });

提交回复
热议问题