MVC - use C# to fill ViewBag with Json Action Result

A Bogus picture A Bogus · Sep 28, 2012 · Viewed 13.5k times · Source

I have an MVC website with C# code behind. I am using an ActionResult, that returns Json.

I am trying to put something in the ViewBag but it doesn't appear to work.

The code looks like this -

    public ActionResult GetStuff(string id)
    {
        ViewBag.Id = id;

        stuff = new StuffFromDatabase(id);

        return this.Json(stuff , JsonRequestBehavior.AllowGet);
    }

The "id" does not appear go in the ViewBag.Id.

Can I put the id in the ViewBag this way? If not any suggestions on how I should do it? Thanks!

Answer

Roberto Conte Rosito picture Roberto Conte Rosito · Sep 28, 2012

Another solution can be this: if you want access "id" property after post action that return json result, you can return a complex object containing all data required:

public ActionResult GetStuff(string id)  
{  
    ViewBag.Id = id;  

    stuff = new StuffFromDatabase(id);  

    return this.Json(new { stuff = stuff, id = id } , JsonRequestBehavior.AllowGet);  
} 

After, in json returned value, you can access all properties like in this example:

$.post(action, function(returnedJson) {
   var id = returnedJson.id;
   var stuff = returnedJson.stuff;
});