Pass a ViewData object when returning JSON in ASP.NET Framework

I’m trying to pass a ViewData object from a controller that’s returning JSON data, but unable to access it from the frontend.

public ActionResult GLSearchView_Read([DataSourceRequest] DataSourceRequest request, DateTime? d = null, DateTime? d2 = null, int aid = 0)
{
    bool creditMemo = true

    ViewData["creditMemo"] = creditMemo;
    var result = Json(GLResearch.Read(aid, d, d2).ToDataSourceResult(request));
    result.MaxJsonLength = int.MaxValue;

    return result;
}

I’m then supposed to use the value of that boolean from the ViewData object to render something conditionally on the frontend. However, I can’t seem to access that ViewData object, am I doing something wrong here?

>Solution :

Setting a ViewData element here doesn’t make any sense because this operation does not result in rendering a view. This operation is just returning data. So if you have additional data to return, return it.

For example, you might define an anonymous object to serialize as your JSON result:

public ActionResult GLSearchView_Read([DataSourceRequest] DataSourceRequest request, DateTime? d = null, DateTime? d2 = null, int aid = 0)
{
    bool creditMemo = true

    var result = Json(new {
        Data = GLResearch.Read(aid, d, d2).ToDataSourceResult(request),
        Memo = creditMemo
    });
    result.MaxJsonLength = int.MaxValue;

    return result;
}

This would create a top-level object which has two properties, each of which being the two different data elements you are returning.

Of course this structure is only a guess. You can structure your data however you want. The overall point is that you would:

  1. Define the structure of the data you want to return to the client.
  2. Populate that structure with your data.
  3. Serialize that structure as JSON sent back to the client.

Leave a Reply