jQuery JsonResult - 如何返回空的 JSON 结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22026158/
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
JsonResult - how to return an empty JSON result?
提问by richard
I have an ajax call that makes a GET request to one of my controllers action methods.
我有一个 ajax 调用,它向我的控制器操作方法之一发出 GET 请求。
The ajax call is supposed to get a JSON response and use that to populate a datagrid. The callback function is supposed to fire and construct the grid and hide the loading indicator.
ajax 调用应该获得 JSON 响应并使用它来填充数据网格。回调函数应该触发并构建网格并隐藏加载指示器。
$.getJSON('@Url.Action("Data", "PortfolioManager")' + '?gridName=revenueMyBacklogGrid&[email protected]', function (data) {
ConstructrevenueMyBacklogGrid(data);
$('#revenueMyBacklogLoadingIndicator').hide();
});
The problem is when the object I am converting to a JsonResult object has no data - it's just an empty collection.
问题是当我转换为 JsonResult 对象的对象没有数据时 - 它只是一个空集合。
returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
In this example it is the collection myYTDSalesClients
that returns empty (which is ok and valid - sometimes there won't be any data).
在这个例子中,它是myYTDSalesClients
返回空的集合(这是正常且有效的 - 有时不会有任何数据)。
The JSON object then returns an empty response (blank, nadda) and since it's not valid JSON, the callback function won't fire. Thus the loading indicator still shows and it looks like it's just loading forever.
JSON 对象然后返回一个空响应(空白、nadda),并且由于它不是有效的 JSON,因此不会触发回调函数。因此加载指示器仍然显示,看起来它只是永远加载。
So, how do I return an empty JSON result {}
instead of a blank?
那么,如何返回空的 JSON 结果{}
而不是空白?
回答by Giovanni Romio
As of asp.net mvc 5 you could simple write:
从 asp.net mvc 5 开始,您可以简单地编写:
Json(new EmptyResult(), JsonRequestBehavior.AllowGet)
回答by Andre Figueiredo
if (portfolioManagerPortalData.salesData.myYTDSalesClients == null) {
returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
}
else {
returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
}
回答by Darío León
In .Net Core 3.0 for a controller of type ControllerBase you can do this:
在 .Net Core 3.0 中,对于 ControllerBase 类型的控制器,您可以执行以下操作:
return new JsonResult(new object());
回答by Kumar Lachhani
Use JSON.NET as a default Serializer for serializing JSON instead of default Javascript Serializer:
使用 JSON.NET 作为默认的 Serializer 来序列化 JSON 而不是默认的 Javascript Serializer:
This will handle the scenario of sending data if its NULL.
这将处理发送数据为 NULL 的情况。
For e.g.
例如
Instead of this in your action method:
而不是在您的操作方法中:
return Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet)
You need to write this in your action method:
你需要在你的动作方法中写下这个:
return Json(portfolioManagerPortalData.salesData.myYTDSalesClients, null, null);
Note: 2nd and 3rd parameter null in above function is to facilitate overloads of Json method in Controller class.
注意:上面函数中的第二个和第三个参数为null是为了方便Controller类中Json方法的重载。
Also you do not need to check for null in all of your action methods like above:
此外,您无需在上述所有操作方法中检查 null:
if (portfolioManagerPortalData.salesData.myYTDSalesClients == null)
{
returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
}
else
{
returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
}
Below is the code for JsonNetResult class.
下面是 JsonNetResult 类的代码。
public class JsonNetResult : JsonResult
{
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult()
{
SerializerSettings = new JsonSerializerSettings();
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting.Indented };
JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
Also You need to add below code in BaseController if any in your project:
如果您的项目中有的话,您还需要在 BaseController 中添加以下代码:
/// <summary>
/// Creates a NewtonSoft.Json.JsonNetResult object that serializes the specified object to JavaScript Object Notation(JSON).
/// </summary>
/// <param name="data"></param>
/// <param name="contentType"></param>
/// <param name="contentEncoding"></param>
/// <returns>The JSON result object that serializes the specified object to JSON format. The result object that is prepared by this method is written to the response by the ASP.NET MVC framework when the object is executed.</returns>
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding)
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding
};
}