I have used ViewBag in .cs file and assigned some values to it.
Now i have to update the ViewBag value in views to something else, can i do that?
For example : Initially
ViewBag.a = 1;
Now in views i have to update the
ViewBag.a = 2;
If i do this action in .cshtml file i'm getting an error.
Asked
Active
Viewed 557 times
0
-
https://stackoverflow.com/questions/39045845/updating-model-from-view – Renat Oct 25 '22 at 07:06
-
browser can only html file, so in an MVC app, we have cshtml file with variables like ViewBag, they will all be rendered to html finally. cshtml and ViewBag are all concepts in server side, what we write in `@{}` in the cshtml are codes in server side. Hence, we can only modify ViewBag value in server side, such as in Controller or in `@{}`, but we can't modify value in javascript code. Could you pls share more details about your requirement so that we can know why and how to help modify the value for ViewBag? – Tiny Wang Oct 25 '22 at 07:57
-
Could you pls let me know what you want to achieve and the detailed error information? – Tiny Wang Oct 27 '22 at 09:34
1 Answers
1
In Contorller, we can set ViewBag.a = 1;
and we can also set ViewBag.a = 2;
in the cshtml file. But it doesn't mean we can modify ViewBag
value directly in javascript code because ViewBag
is a server side variable, but js is client side code.
I did a test in my side, Controller like
public IActionResult Index()
{
ViewBag.a = "value from controller";
return View();
}
And In my index.cshtml:
@{
ViewData["Title"] = "Home Page";
ViewBag.a = "value from View";
}
<div>@ViewBag.a</div>
<button id="btn1">change ViewBag</button>
@section Scripts{
<script>
$("#btn1").click(function(){
alert(1);
@{ViewBag.a = "value from javascript";}
});
</script>
}
Then the page looks like below, click the button won't change the content.

Tiny Wang
- 10,423
- 1
- 11
- 29