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

I have an MVC site with C # code. I am using ActionResult which returns Json.

I am trying to put something in the ViewBag, but it does not work.

The code looks like this:

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

        stuff = new StuffFromDatabase(id);

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

"id" does not appear in ViewBag.Id.

Is it possible to put an identifier in a ViewBag this way? If not any suggestions on how I should do this? Thank!

+5
source share
3 answers

Another solution may be the following: if you want to access the id property after post action returning the json result, you can return a complex object containing all the necessary data:

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

    stuff = new StuffFromDatabase(id);  

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

, json , :

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

ViewBag . json , -. json :

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

Are you trying to install ViewBag.Idas a result of Json? ViewBagused in representations, not in Json.

Added

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

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

Then you can access this data in javascript.

+1
source

All Articles