Is it possible to use a value from javascripts in razor asp.net?

Suppose I have the following javascripts value:

<script type="text/javascript">
    var variable_js=10;
</script>

And in razor, a variable of asp.net, I want you to assign the value of javascripts that you declare. For example:

@Dim variable_vb=variable_js '¿se puede??

Can something like the above be done?and how?

 1
Author: Danilo , 2016-05-15

2 answers

What you are trying to do is not possible. Something that is important to understand between code in Razor and javascript, that the former is processed on the server side and the other is executed on the client (i.e. the browser).

When you make a request for a certain page, that page is processed on the server and after being received by the browser, the client-side code (javscript, css, html, etc.) is processed.

Therefore, as you can conclude it is not possible to do what you mention. What you could achieve is reverse behavior, processing something on the server, and writing to a javascript code. Something like the following

<script type="text/javascript">
   var variable_from_server= '@Model.Variable_From_Server';
</script>

I hope it was clear and helpful.

Greetings

 1
Author: hdlopez, 2016-05-15 21:35:54

Directly can not... and although it's not the best way, it occurs to me that you can generate a method with JS that calls a controller function and thus deliver it the value you have in JS.

Example:

[HttpPost] 
public ActionResult ValorDesdeJS(string valueJS)
{
     //Tu código o asignación de variables a lo que necesites...
}

And from JS you could call a function like this:

function checkValidId(checkId)
{
    $.ajax({
         url: 'controllerName/ValorDesdeJS',
         type: 'POST',
         contentType: 'application/json;',
         data: JSON.stringify({ valueJS: TuValorJS}),
         success: function (respuesta)
         {
              //código... 
         }
    });
}

After that, if you want to show it in the view you would have to pass it through a viewbag.

 0
Author: Sebastian Martinez, 2016-12-18 15:50:15