asp.net mvc返回Json数据
主要介绍了mvc使用JsonResult返回Json数据。
00新建控制器DefaultController
controller 中定义以下方法:
01返回一个自定义的object数组
//01返回一个自定义的object数组
public ActionResult Index()
{
var res = new JsonResult();
var name = "小华";
var age = "27";
var name1 = "小明";
var age1 = "26";
res.Data = new object[] { new { name, age }, new { name1, age1 } };//返回一个自定义的object数组
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取,否则用GET获取是会报错。
return res;
}
预览
/default/index
02返回单个对象;
//02返回单个对象;
public ActionResult Index2()
{
var res = new JsonResult();
var person = new { Name = "小明", Age = 27, Sex = "男" };
res.Data = person;//返回单个对象;
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取,否则用GET获取是会报错。
return res;
}
预览
/default/index2
03返回一个字符串,意义不大;
//返回一个字符串,意义不大;
public ActionResult Index3()
{
var res = new JsonResult();
res.Data = "这是个字符串";//返回一个字符串,意义不大;
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取,否则用GET获取是会报错。
return res;
}
预览
/default/index3
完整代码
DefaultController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC之接口返回json数据.Controllers
{
public class DefaultController : Controller
{
// GET: Default
//01返回一个自定义的object数组
public ActionResult Index()
{
var res = new JsonResult();
var name = "小华";
var age = "27";
var name1 = "小明";
var age1 = "26";
res.Data = new object[] { new { name, age }, new { name1, age1 } };//返回一个自定义的object数组
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取,否则用GET获取是会报错。
return res;
}
//02返回单个对象;
public ActionResult Index2()
{
var res = new JsonResult();
var person = new { Name = "小明", Age = 27, Sex = "男" };
res.Data = person;//返回单个对象;
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取,否则用GET获取是会报错。
return res;
}
//03返回一个字符串,意义不大;
public ActionResult Index3()
{
var res = new JsonResult();
res.Data = "这是个字符串";//返回一个字符串,意义不大;
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取,否则用GET获取是会报错。
return res;
}
}
}