I dug up an old answer of mine which addresses this very topic. What you want is not possible, you are misunderstanding what the ViewBag
is an how it should be used.
Below is a copy of the linked answer. Note that the original question asked how to do it with jQuery, but the answer itself applies equally to your case.
You're misunderstanding how the ViewBag works.
When working in MVC, and you open a webpage, this is what (roughly) happens:
- The Method 'Index' of FooController is run. At the end, a View is returned.
- Your MVC application will then find the view for you, and start rendering it according to the HTML it finds in the related .aspx file. If the program encounters items such as "@ViewBag.Id", it will basically do a string replace with whatever the ".Id" value is. (It's a bit more complicated than that, but for the sake of argument, it basically does a string replace).
- After rendering, the HTML document is sent to your browser, who then displays it.
By the time your browser gets the page, your ViewBag has basically gone 'out of scope'. This is because your ASP (MVC) application uses the ViewBag, but Javascript only has a scope in the web browser document (this is the HTML code that was returned to the the browser by the application, after the ViewBag has gone out of scope. Javascript isn't part of the MVC application, only the resulting webpage.
So the short answer is, no you can't do it like that. Try to think of it as doing an inline string replace.
You can only put the ViewBag value into the HTML page, not the other way around.
Suppose your Id is 5, the following code in the aspx file:
$(".btn").on("click",function(){
@ViewBag.Id = $(this).attr("id")
});
Will be sent to the browser as
$(".btn").on("click",function(){
5 = $(this).attr("id")
});
Since your browser only sees this last part, it just doesn't make sense in Javascript. In you case, With the syntax error, it just means your variable hasn't been initialised, and you are trying to access a null
.
For you, the issue is still the same. ViewBag is only used when rendering the webpage. By the time your browser loads the page (and any subsequent user actions on the page) the ViewBag has already been discarded.
Even if you could update it somehow, it wouldn't do anything with the updated value. It has already rendered the view it needed to.
If you want something to happen on the page, then you must change it on the page itself (using JS directly, or a JS library).