0

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?

0

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

This makes sense, I'm going to have to dig in a level deeper instead of passing a ViewData object. Thanks for clarifying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.