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

1

Suppose I have the following value of javascripts:

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

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

@Dim variable_vb=variable_js '¿se puede??

Is it possible to do something like that stated above and how?

    
asked by Danilo 15.05.2016 в 22:32
source

2 answers

1

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

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

Therefore, as you can conclude it is not possible to do what you mention. What you could achieve is the inverse behavior, process something on the server and write in 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 useful.

Greetings

    
answered by 15.05.2016 / 23:35
source
0

Directly you can not ... and although it is not the best way, it occurs to me that you can generate a method with JS that calls a function of the controller and thus give you 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.

    
answered by 18.12.2016 в 16:50