how to pass value to razor variables from JavaScript?


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

 


Asked by:- pika
1
: 26696 At:- 7/17/2017 3:58:58 PM
JavaScript jquery C# MVC asp-net

I think your question is not correct, please check it again In title, you have asked 'how to pass razor value to javascript' while in example code you are trying to get value in razor from javascript, which is not possible 0
By : vikas_jk - at :- 7/18/2017 7:06:33 AM
Ok, updated my question, I would like to know about how to pass a value to razor from javascript? 0
By : pika - at :- 7/18/2017 7:25:34 AM






2 Answers
profileImage Answered by:- vikas_jk

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.

2
At:- 7/18/2017 7:40:18 AM
ok, I was trying to load value in @ViewBag.Theme= localStorage.getItem('style_color'); but failed as per your above answer 0
By : pika - at :- 10/16/2017 11:49:47 AM


profileImage Answered by:- Vipin

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>
1
At:- 9/5/2017 4:32:22 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use