I just want to ask, is there a way to set up the viewbag value dynamically using jquery? I try this code in my script,
$(".btn").on("click",function(){
@ViewBag.Id = $(this).attr("id")
});
i dont know if its correct but when i try to run my MVC 3 Project, this error appear in my firebug
Syntax Error
= $(this).attr("id")
Please Help. Thanks
In the above figure, it attaches Name property to ViewBag with the dot notation and assigns a string value "Bill" to it in the controller. This can be accessed in the view like @ViewBag.Name. You can assign a primitive or a complex type object as a value to ViewBag property.
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.
The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed in the cshtml file (View) using Razor syntax in ASP.Net MVC Razor.
To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.
You're misunderstanding how the ViewBag works.
When working in MVC, and you open a webpage, this is what (roughly) happens:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With