Access Server side variable on client side and Vice versa Asp.Net and javascript

I have a requirement of adding server side variables in client side and other way round. Because I need to set a value from client side using javascript and access the same in code behind page.

I have to use C#.Net and javascript.

Any directions please

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can simply write out variables to the javascript using code blocks (<%%>):

var mJSVariable = <%:myServerSideVariable%>;

To do the opposite, the easiest thing it to write the JS value into a server side hidden form field and pick it up on the server side:

<input type="hidden" id="myHiddenId" runat="server" />

// Javascript
var myHidden = document.getElementById("<%:myHiddenId.ClientId%>");
myHidden.value = myJSVariable;

// Code behind
var myJSVariableValue = myHiddenId.Value;

Method 2

you can declare some variable at server side .cs file like public int myServerSideINT and can access it on .aspx file using

   <script type="text/javascript">
   function getServerSideVAR()
   {
        var serverVAR=<%= this.myServerSideINT %>;
   }
   </script>

i hope this will helpful to you

Method 3

The way I normally do it is via an ASP.NET HiddenField.

in JS you can set it via (JQuery example):
$("input[Name$='_IDofField']").val(<newvalue>);
On ASP.NET you can access it via the IDofField.Value property.

Method 4

It is possible to store JavaScript variable values into server side variable. All you have to do is to implement System.Web.UI.ICallbackEventHandler class.

Below is the code demonstrating how to do it.

In aspx Page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Client Calback Example</title>
    <script type="text/ecmascript">
    function LookUpStock()
    {
        var lb=document.getElementById("tbxPassword");
        var product=lb.value;
        CallServer(product,"");
    }

    function ReceiveServerData(rValue){
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input type="password" id="tbxPassword" />
            <input type="Button" onclick="LookUpStock">Submit</button>
        </div>
    </form>
</body>

In Code Behind (CS) Page:

public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
    String cbReference = Page.ClientScript.GetCallbackEventReference
    (this,"arg", "ReceiveServerData", "context");
    String callbackScript;
    callbackScript = "function CallServer(arg, context)" +
    "{ " + cbReference + ";}";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
    "CallServer", callbackScript, true);
}
public void RaiseCallbackEvent(String eventArgument)
{
    if(eventArgument == null)
    {
        returnValue = "-1";
    }
    else
    {
        returnValue = eventArgument;
    }
}
public String GetCallbackResult()
{
    return returnValue;
}
}

Now you can get the JavaScript variable product value into Server side variable returnValue.

Method 5

I have had a situation where a HiddenField was not usefull to pass a value from javascript to APS.net at serverside. My script was reading a value and then calling to code in server side but the value on hidden field was not updated yet on ASP.net hiddenfield control.
The only solution I’ve found was to write the value in a cookie with javascript and later read it on ASP.net page.

on javascript:

function setCookie(cname, cvalue, exdays, path) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    if (path != undefined)
    expires += "; path=" + path;
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

setCookie("currentDbCompras", _currentDb);

and at server side

Request.Cookies("currentDbCompras").Value

I hope it helps!!!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x