7

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!

tereško
  • 58,060
  • 25
  • 98
  • 150
A Bogus
  • 3,852
  • 11
  • 39
  • 58

3 Answers3

4

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;
});
Roberto Conte Rosito
  • 2,080
  • 12
  • 22
  • I actually need to access it inside C# POST code. I want to store the id in the ViewBag.Id then reference the ViewBag.Id when I do a POST. – A Bogus Sep 28 '12 at 15:07
  • I am going to use this RoBYCoNTe (along with some other code) Thanks! – A Bogus Sep 28 '12 at 16:56
3

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);
DavidWainwright
  • 2,895
  • 1
  • 27
  • 30
1

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.

webdeveloper
  • 17,174
  • 3
  • 48
  • 47