Reputation: 4733
I want to assign viewbag to my javascript variable to compare some value from model
<script>
var uid = "..."; // this retrieves some variable from external server
@ViewBag.someId = uid;
</script>
...
@If(Model.AppDataFbId == ViewBag.someId){ ... }
But this throws an exception:
Uncaught SyntaxError: Unexpected token =
What can I do?
Upvotes: 2
Views: 1097
Reputation: 858
The variable @ViewBag.someId
is used by the server to generate the static HTML page it sends to the browser. It doesn't make sense for the browser to be able to directly change that variable on the server after it receives the HTML.
It looks like you want the value of uid
to decide the page contents. If you want these changes to be made server-side (i.e. before the page is sent to browser) then you will have to get your MVC controller to grab this value from the external server before it returns its view. A more conventional way to solve the same problem is to transform the page in the browser with Javascript.
Upvotes: 1
Reputation: 436
As the comment said , ViewBag is server side code, you can't set ViewBag with js variables in C# code block but you can set js variables with ViewBag value. Like:
<script>
var uid ='@ViewBag.someId';
</script>
If you just want compare Model.AppDataFbId with js variable(uid), add the logic in js code.
<script>
function compare(){
if('@Model.AppDataFbId'==uid){
//other code
}
}
</script>
Upvotes: 2