ASP.NET MVC返回JSON结果? [英] ASP.NET MVC Return Json Result?

查看:863
本文介绍了ASP.NET MVC返回JSON结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着返回JSON结果(数组);
如果我做手工它的工作原理

Im trying to return a json result (array); If I do it manually it works

    resources:[
{
    name: 'Resource 1',
    id: 1,
    color:'red'
},{
    name: 'Resource 2',
    id: 2
}],

但具有由它传递渲染问题IM:

but im having issues rendering by passing it in:

在该视图:

 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格式呈现:

But looking at whats rendered in html:

resources:System.Web.Mvc.JsonResult

任何想法,我去错了?

Any ideas where im going wrong?

推荐答案

它应该是:

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

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

或者更简单地说:

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

我做您呼叫从另一个其中的ActionResult不会工作GetResources()的通知。如果你正在寻找让JSON回来,你应该调用从阿贾克斯GetResources()直接...

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

这篇关于ASP.NET MVC返回JSON结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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