【问题标题】:ASP.NET MVC Return Json Result?ASP.NET MVC 返回 Json 结果?
【发布时间】:2013-05-26 01:03:11
【问题描述】:

我正在尝试返回一个 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的可能重复
  • 应该是:return Json(new { Data = model } , JsonRequestBehavior = JsonRequestBehavior.AllowGet);

标签: jquery asp.net-mvc json


【解决方案1】:

应该是:

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()...

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2013-08-10
    • 2018-07-22
    • 1970-01-01
    相关资源
    最近更新 更多