ASP.NET MVC返回Json结果?

40

我想返回一个JSON结果(数组);

如果我手动做,它可以工作。

    resources:[
{
    name: 'Resource 1',
    id: 1,
    color:'red'
},{
    name: 'Resource 2',
    id: 2
}],
但我遇到了传递它并呈现的问题:
在视图中:
 resources:@Model.Resources

在控制器上是哪个

public ActionResult Index()
        {
...
var model = new Display();
model.Resources = GetResources();
}
 public JsonResult GetResources()
        {
            var model = new Models.ScheduledResource()
                {
                    id = "1",
                    name = "Resource"
                };
            return new JsonResult() { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

按照这个模型

public JsonResult Resources { get; set; }

但是看HTML呈现的内容:

resources:System.Web.Mvc.JsonResult

有什么想法我做错了吗?


可能是JSONResult to String的重复问题。 - James
应该是:return Json(new { Data = model } , JsonRequestBehavior = JsonRequestBehavior.AllowGet); - Steve
1个回答

84

它应该是:

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

更简单地说:

return Json(model, JsonRequestBehavior.AllowGet); 

我注意到您正在从另一个ActionResult调用GetResources(),这样是行不通的。如果您想要获取JSON返回值,则应直接从ajax调用GetResources()...


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