12

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

1
  • post your related part of code Commented Dec 9, 2010 at 9:51

5 Answers 5

28

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;
Sign up to request clarification or add additional context in comments.

4 Comments

1) in your example, could you have written Hidden form field to js variable. 2) could we do this: var mJSvar = <%: Model.FirstNameProperty %>
@VoodooChild - 1) You could, and that's how I would if I was using JS files and no inline JS. 2) Sure, but if FirstNameProperty is a string, you should put the whole <%:%> block in single or double quotes.
Thanks! Regarding #2 - lets say I have a separate JS file and no inline, would I still be able to reference my Model? (I am a beginner in MVC and JavaScript - and still getting used to alot of concepts)
@VoodooChild - You should be able to, so long as the variable is not encapsulated in a closure (that is, it is "public").
6

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

2 Comments

Good solution. Note: Strings always have to begin and end with ', otherwise this wont work (Example: serverVAR='<%= this.myServerSideString %>';). Btw: Why is this shown as a synatxerror to me?
@BudBrot - you just saved me another hour of wondering why my very simple code wasn't working. Very helpful.
1

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.

Comments

1

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.

Comments

0

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!!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.