How can I pass value to razor variables from JavaScript in .cshtml(razor) page (asp.net mvc C#)?
Something like this
@{
int x = 0;
}
<script>
var y = 1;
@x = y;
</script>
Is it possible? Thanks
This is not possible, you cannot pass value from javascript to razor because both are not present at the same time, Razor is server side language while javascript is client side language, razor doesn't exist anymore after the page was sent to the "Client side".
You can change HTML/CSS/Javascript using razor variables, but it is not true for vice-versa. When the server gets a request for a view, it creates the view with only HTML, CSS and Javascript code. No C# code is left, it's all get "translated" to the client side languages.
You can check your page source from the browser you will not any C# code, all is converted into HTML,CSS,Javascript.
May be using this, not a proper solution, but you can create hidden field and set it using javascript, something like
@Html.Hidden("MyId", 0);
And javascript would be
<script>
//Call this using Onbutton click or when you want
function SetHiddenValue(value) {
$('#MyId').val(value);
}
</script>
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly