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

3

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!

Jornada answered 28/9, 2012 at 14:38 Comment(7)
How are you using ViewBag in the View?Kegan
I actually just want the value I put in the ViewBag to be accessible in my C# code when I do a POST. Like - var currentId = ViewBag.IdJornada
I'm confused.. as you are already passing id as an argument?Kegan
The id is not in the "stuff" that I am returning in the Json object. I want to do a POST to C# code behind like [HttpPost] public ActionResult GotStuf(FormCollection formCollection) { var currentId = ViewBag.Id; }Jornada
So you want to set ViewBag.Id in the View..Kegan
According to "webdeveloper" below. It doesn't sound like I can do what I am trying to do. Thanks everyone!Jornada
Yes (to your last comment Lews Therin)Jornada
V
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;
});
Vein answered 28/9, 2012 at 14:53 Comment(2)
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.Jornada
I am going to use this RoBYCoNTe (along with some other code) Thanks!Jornada
R
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);
Remembrance answered 28/9, 2012 at 14:52 Comment(0)
S
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.

Serra answered 28/9, 2012 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.