如何从MVC返回JSON数据?

时间:2011-06-13 02:51:49

标签: asp.net-mvc json

我目前正在返回这样的JSON数据:

return new JsonResult {
Data = from service in _serviceTable.GetAll(
 u => u.PartitionKey == "1Z0-851" & 
 u.RowKey.CompareTo(lowerBound) >= 0 & 
 u.RowKey.CompareTo(upperBound) < 0)
       select new { 
 service.PartitionKey, 
 service.RowKey,
 service.TopicDescription,
 service.SubTopicDescription,
 service.Weight,
 service.Format,
 service.Style,
 service.ShortTitle }
};

这很好但现在我想返回一些数据来表明状态。我尝试以这种方式添加此状态:

 ShortTitle },
 Status = "abc"
    };

但是我收到一条语法错误消息,说“不包含状态定义

有人可以解释我如何添加状态并将其发送回我的网页。请注意,serviceTable中有许多行,但只有一个状态要发回。

2 个答案:

答案 0 :(得分:3)

你可以通过使用几个中间变量(var轻松处理匿名类型)来做到这一点并清理一下:

var service = from service in _serviceTable.GetAll(
                u => u.PartitionKey == "1Z0-851" & 
                u.RowKey.CompareTo(lowerBound) >= 0 & 
                u.RowKey.CompareTo(upperBound) < 0)
              select new { 
                service.PartitionKey, 
                service.RowKey,
                service.TopicDescription,
                service.SubTopicDescription,
                service.Weight,
                service.Format,
                service.Style,
                service.ShortTitle });

var status = "abc";

var result = new {
  Service = service,
  Status = status
};

return Json(result);

答案 1 :(得分:1)

return new JsonResult {
Data = new {Result=(from service in _serviceTable.GetAll(
 u => u.PartitionKey == "1Z0-851" & 
 u.RowKey.CompareTo(lowerBound) >= 0 & 
 u.RowKey.CompareTo(upperBound) < 0)
       select new { 
 service.PartitionKey, 
 service.RowKey,
 service.TopicDescription,
 service.SubTopicDescription,
 service.Weight,
 service.Format,
 service.Style,
 service.ShortTitle}), Status="abc"}


};

请检查语法,但是你明白了。 要访问数据,您必须使用data.Result和data.Status等状态。