【问题标题】:Get list of objects from jquery get in mvc从jquery获取对象列表在mvc中
【发布时间】:2023-03-30 22:10:01
【问题描述】:

我想要的是在 jquery GET 的返回中获取对象列表: 这是我的看法:

 public List<CarBrandModel> Index()
    {
        //get the list of carbrand
        List<CarBrandModel> modelList = CarBrandModel.FromEntityToModel(service.GetAll());
        return modelList;
    }

这是我的模型:

    public class CarBrandModel
    {
      public int Id { get; set; }
      public string Name { get; set; }
      public string Description { get; set; }
    }

这是我的 js:

var get = function () {
$.ajax({
    url: '/carbrand/Index',
    accepts: 'application/json',
    dataType: false,
    cache: false,
    type: 'GET',
    success: function (data) {

    }
});


};
get();

但数据中的结果是: “System.Collections.Generic.List`1[CarsWebProject.Models.CarBrandModel]” 而是我想要的 json 对象列表。 当我使用 web api 时,我能够使用相同的代码但使用 web api 的 get 函数获取 json 对象的列表。但这里我只使用 mvc .net。

我可以修复什么来获取 json 对象列表。

有一个图书馆或其他东西可以使用,并且必须领导每个帖子或获取。

【问题讨论】:

  • 如果你想要 json,那么你需要返回 json - public JsonResult Index() { .... return Json(modelList, JsonRequestBehavior.AllowGet); } 但是你的代码还有一些其他问题,例如 data 将不包含名为 total 的属性,它应该是`dataType:'json,'
  • 是的,我编辑了那个,所以请编辑以免人们混淆
  • 但是没有办法返回对象,某种架构?
  • 不清楚你最后的评论是什么意思。你说你想返回 json(CarBrandModel 对象的集合),这是我的第一条评论展示的方法。
  • 你是对的,只有使用webapi才能将模型序列化返回。 encosia.com/asp-net-web-api-vs-asp-net-mvc-apis

标签: jquery .net ajax json asp.net-mvc


【解决方案1】:

你必须将结果写成 Json。

 public async Task<ActionResult> Index()
    {
        //get the list of carbrand
        List<CarBrandModel> modelList = CarBrandModel.FromEntityToModel(service.GetAll());
        return Json(new { Data = modelList}, JsonRequestBehavior.AllowGet); 
    }

【讨论】:

    【解决方案2】:

    正如@Stephen Muecke 在 mvc 中所说,返回 json 列表的方式是:

     public JsonResult Index()
     {
        //get the list of carbrand
        List<CarBrandModel> modelList = CarBrandModel.FromEntityToModel(service.GetAll());
        return Json(modelList, JsonRequestBehavior.AllowGet);
     }
    

    另一方面,如果你使用 web api,返回对象列表的方法是:

     public List<CarBrandModel> Get()
     {
        //get the list of carbrand
        List<CarBrandModel> modelList = CarBrandModel.FromEntityToModel(service.GetAll());
        return modelList;
     }
    

    所以斯蒂芬的答案是正确的。我的困惑是因为我总是使用 web api,现在只使用 mvc。

    【讨论】:

      猜你喜欢
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多