如何从MVC控制器返回json数据? [英] How to return json data from MVC controller?

查看:810
本文介绍了如何从MVC控制器返回json数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的型号:

  public   class 学生
{
public int Id {获得; set ; }
public string 名称{ get ; set ; }
public int RollNo { get ; set ; }
}





我的控制器:

  public   class  HomeController:Controller 
{
private 实体db = new 实体();

public ActionResult List()
{
var std = 来自 s db.Students
选择;
return Json(std, Student ,JsonRequestBehavior.AllowGet);
}
}





输出:

 [
{ Id:1,Name:Shan,RollNo:1},
{Id:2,Name:Ali,RollNo:2},
{Id:3,姓名:Ahmed,RollNo:3}
]



我的问题是如何转换此结果如下:



 {
-Student:
[
- {Id: 1,姓名:Shan,RollNo:1},
- {Id:2,姓名:Ali,RollNo:2},
- { Id:3,姓名:Ahmed,RollNo:3}
]
}





我尝试了什么:



我想要输出如下:

 {
- 学生:
[
- {Id:1,姓名:Shan,RollNo:1},
- { Id:2,Name:Ali,RollNo:2},
- {Id:3,Name:Ahmed,RollNo:3}
]
}

解决方案

  return  Json( new  {Student}, JsonRequestBehavior.AllowGet); 


My Model:

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int RollNo { get; set; }
    }



My Controller:

public class HomeController : Controller
{
   private Entities db = new Entities();

   public ActionResult List()
   {
      var std = from s in db.Students
      select s;
      return Json(std, "Student", JsonRequestBehavior.AllowGet);
   } 
}



Output:

[
   {"Id":1,"Name":"Shan","RollNo":1},
   {"Id":2,"Name":"Ali","RollNo":2},
   {"Id":3,"Name":"Ahmed","RollNo":3}
]


My Problem is that how to convert this result as below:

{
  -Student:
   [
      - {"Id":1,"Name":"Shan","RollNo":1},
      - {"Id":2,"Name":"Ali","RollNo":2},
      - {"Id":3,"Name":"Ahmed","RollNo":3}
   ]
}



What I have tried:

I want the output as below:

{
  - Student:
  [
     - {"Id":1,"Name":"Shan","RollNo":1},
     - {"Id":2,"Name":"Ali","RollNo":2},
     - {"Id":3,"Name":"Ahmed","RollNo":3}
  ]
}

解决方案

return Json(new {Student}, JsonRequestBehavior.AllowGet);


这篇关于如何从MVC控制器返回json数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆