jQuery ASP.NET MVC 返回 Json 结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16836428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC Return Json Result?
提问by D-W
I'm trying to return a JSON result (array);
我正在尝试返回一个 JSON 结果(数组);
If I do it manually it works
如果我手动执行它可以工作
resources:[
{
name: 'Resource 1',
id: 1,
color:'red'
},{
name: 'Resource 2',
id: 2
}],
but I'm having issues rendering by passing it in:
但我在通过传递它时遇到了问题:
On the view:
在观点上:
resources:@Model.Resources
Which on the controller
哪个在控制器上
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 };
}
on the model
在模型上
public JsonResult Resources { get; set; }
But looking at whats rendered in HTML:
但是看看在 HTML 中呈现的内容:
resources:System.Web.Mvc.JsonResult
Any ideas where I'm going wrong?
任何想法我哪里出错了?
回答by Steve
It should be :
它应该是 :
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);
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...
我确实注意到您正在从另一个无法工作的 ActionResult 调用 GetResources()。如果你想找回 JSON,你应该直接从 ajax 调用 GetResources() ......