Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 792
A Bogus Avatar asked Sep 28 '12 14:09

A Bogus


1 Answers

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;
});
like image 146
Roberto Conte Rosito Avatar answered Sep 18 '22 17:09

Roberto Conte Rosito