如何使用jQuery AJAX从MVC控制器获取列表到视图?

14

我需要通过jquery ajax从mvc控制器获取列表并在视图中显示。我该怎么做?这是我的代码。它正在发出错误消息。

在控制器中

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

鉴于

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

    }

在此输入图像描述


将方法返回类型更改为ActionResult,并将列表作为return Json(new { MyList = FodList }, JsonRequestBehavior.AllowGet);返回。 - markpsmith
问题解决了...??? - Kartikeya Khosla
5个回答

19

为什么你要在GET方法中使用HttpPost? 并且需要返回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');
        }
    });

}

这个解决方案对我来说非常棒。当我向主要开发人员展示这个解决方案时,他问我:“为什么使用JsonRequestBehavior.AllowGet?”抱歉,我不知道,我回答道。他建议我进行研究以了解它,然后就清楚多了:https://dev59.com/Smoy5IYBdhLWcg3wkO6g#8464685 - AuroMetal
@IMAK,为什么不呢?反正它最终会被序列化成JSON对象中的数组。 - Igor Semin

6

您可以这样做,返回JSON数据并将其打印:

阅读完整教程: 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.');

                }

            });

1
我之所以没有得到结果是因为...我忘记在库中添加json2.js文件。
 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');
        }
    });

}

0
   $(document).ready(function () {
        var data = new Array();
        $.ajax({
            url: "list",
            type: "Get",
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index) {
                    // alert("id= "+data[index].id+" name="+data[index].name);
                    $('#myTable tbody').append("<tr class='child'><td>" + data[index].id + "</td><td>" + data[index].name + "</td></tr>");
                });

            },
            error: function (msg) { alert(msg); }
        });
    });


    @Controller
    public class StudentController
    {

        @Autowired
        StudentService studentService;
        @RequestMapping(value= "/list", method= RequestMethod.GET)

        @ResponseBody
        public List<Student> dispalyPage()
        {

            return studentService.getAllStudentList();
        }
    }

0

试试这个:

视图:

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

        FoodList = FoodService.getFoodDetails(userId);

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

控制器:

function GetFoodDetails() {
    debugger;
    $.ajax({
        type: "GET",       // make it get request instead //
        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('error');
        }
    });

}

如果ajax请求出现问题,您可以使用以下方式:$.getJSON

$.getJSON("Food/getFoodDetails", { userId: Id } , function( data ) {....});

抱歉,它无法工作!它进入了错误部分。 - Aiju
只需查看更新的答案,它会起作用。@AijuThomasKurian - Kartikeya Khosla
我需要在routesconfig中更改任何内容吗? - Aiju
只需检查您的操作... public JsonResult getFoodDetails(int userId)...如果来自ajax的userid为null或为空...那么它会创建问题,或者像我在答案中使用的那样使用"?"与int一起...@AijuThomasKurian - Kartikeya Khosla
尝试使用$.getJSON而不是ajax..只需查看更新的答案..@AijuThomasKurian - Kartikeya Khosla
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接