No response received with JsonResult in MVC 6

浪子不回头ぞ 提交于 2019-12-05 10:08:40

I suspect the below code, DataTable / dynamic to JSON ???

**var result = new DataTablesResult();**

List<MyClass> myClass = await _Repository.GetListMyClass();

**result.Data = new List<dynamic>(myClass);**
var resultado = new
{
    data = result.Data.ToArray()
};

It doesn't covert to JSON ... right ?

I noticed that you set property ReferenceLoopHandling to Newtonsoft.Json.ReferenceLoopHandling.Ignore. As I know, the settings for the JSON output formatter and for JsonResult are now separate. If MyClass has cycles, an error occurs in Json.net.

Self referencing loop detected

There are two solutions in this case:

1) Use a custom serialize settings for the controller method:

var settings = new JsonSerializerSettings
{
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
return Json(result, settings);

2) Configung a shared settings between JsonResult and the formatter in the Startup:

public void ConfigureServices(IServiceCollection services)
{
    //some configuration

    services.AddMvc()
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });
}

I hope this will help you

You don't need to return a Json explicitly. Try returning your object directly. You can limit the output to json with the [Produces] attribute if you like, or get advantage of content negotiation for format may be wiser.

public async Task<DataTablesResult> Get()
{
    var result = new DataTablesResult();
    List<MyClass> myClass = await _Repository.GetListMyClass();

    result.Data = new List<dynamic>(myClass);
    var resultado = new
    {
        data = result.Data.ToArray()
    };

    return Ok(resultado);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!