Search code examples
c#ajaxapigetviewbag

How to get the value of ViewBag in C# (MVC or Core) when calling API?


I use an $.Ajax to call C# API to get data, in the Home controller in Index Action I defined a ViewBag:

public IActionResult Index()
{
     ViewBag.UserInfo = "TEST";
     return View();
}

Inside the Get API Action:

[HttpGet("Get")]
public IActionResult Get()
{ 
     var x = ViewBag.UserInfo;
     return Json(new { result = x});
}

But when I call the API and debug the code, I found that "x" is empty

Please advise


Solution

  • You can't do that. You are trying to get data from the View in the controller via Viewbag.

    This only works the other way around

    • Controller action to view. Ok
    • View to controller action. Can't be done
    • View (ajax or otherwise) to controller action. Can't be done
    • Api call to view. Can't be done.

    Only mvc actions return viewbag data, as the values and page are created in the code behind

    Think about it this way. When you are setting the viewbag, this has a value on your web server.

    The web server, while serving your request, will create a full html to reply to the user. In there it will use the view bag values.

    Once the client gets the html page, there is no viewbag anymore. The value might be there so you can post it back, but you can't access it the way you are trying.