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

14,210

Solution 1

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;
});

Solution 2

ViewBag is only available server-side. You are sending a json string back to the browser, presumably the browser then does something with it. You will have to send the id in the json response as follows:

return this.Json(new { Id = id, Data = stuff }, JsonRequestBehaviour.AllowGet);

Solution 3

You trying to set ViewBag.Id in Json result? ViewBag used in views, not in Json.

Added

As I can see from comments, then you trying to use it in javascript, you can do such things. Try this:

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

Then you can access this data in javascript.

Share:
14,210
A Bogus
Author by

A Bogus

Updated on June 05, 2022

Comments

  • A Bogus
    A Bogus almost 2 years

    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!