Вопрос

I know that we can use eval and access the public property in declared in the C# code to access the server side variable. however this is not recommended as the safest way to do this. what is the best ways to access the server variable in java-script? Please give examples of ASP.Net web forms?

Это было полезно?

Решение

The variables on server side, lives in different universe than the variables on the client side. This two universe are on different computers and the only communication between of them is the View of a page, and the post back to the server.

So the first is to give the variable from code behind on the render of the html page to the javascript as a number, eg:

<script>
 var OurVariable = 334;
</script>

To render that you have many options, eg you can use a Literal and render it on code behind as:

<asp:Literal runat="server" ID="txtScriptOnMe" />

and on code behind:

txtScriptOnMe.Text = "<script> var OurVariable = 334; </script>";

Now you have actually send the 334 on the client side. After your modification with the javascript the next step is to send back the new number on server - and this can be done only on PostBack, or with Ajax Call, and by the use of a hidden input.

Eg you have this input <input id="hidden1" type="hidden" runat="server" /> and using javascript you can change the value of it and send it back to the server side, then read it from code behind, and there you go - you have a communication from variables on code behind and on javascript.

Eg, you can write on javascript

OurVariable = 221;
document.getElementById("<%=hidden1.ClientID%>").value = OurVariable;

and change that to 221, and send that on code behind

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top