Passing javascript variables to server-side C# logic

Is there a way to assign/pass/copy a javascript variable to a server side variable in C#? For the sake of argument, let's say that I was able to parse some JSON for variables that I want to store and assign them on the client (ie. var = FirstName and var = 25 and var = someDateTime, etc) .

Answers:

Answer

Javascript variables exist on the client so in order to get those values into the server you'll need to execute a request from the client. You probably want an approach called AJAX. AJAX involves Javascript making requests to the server in the background of your page. You'll set up a C# web page that expects these background requests. If you use a GET request then then place the variables in the query string of your AJAX request to your new C# page. If you want to use a POST request then you'll set parameters in the data that you post to your page.

Libraries like jQuery make this kind of thing pretty simple.

Answer

There's no direct way to access variables in client-side code from your server-side code.

An easy way, without writing handlers, ajax posts, etc., to accomplish this is to simply store the java script variable in a hidden text box and retrieve it on your post. You can also write back to the hidden field and feed your script with the value, e.g.

Markup

<asp:HiddenField runat="server" Id="JavascriptValue" value="0">

Script

<script>
   var myValue = <%=JavascriptValue.Value%>
</script>

Server-Side

protected void Page_Load(object sender, EventArgs e)
{
string val = JavascriptValue.Value;
}
Answer

Write the value to a control (e.g. HiddenField) via JS and read that on the postback.

You can register hidden fields from code-behind on the Page_Load

if (this.Request.Form["myHiddenField"] == null) { 
    ClientScript.RegisterHiddenField("myHiddenField", ""); }

populate it with a script

ClientScript.RegisterOnSubmitStatement(this.GetType(),
     MethodBase.GetCurrentMethod().DeclaringType.Name + "_myHiddenField",
     "var res=document.getElementById('myHiddenField');if(res!=null){res.value='some value';}");

and read it on postbacks (also Page_Load)

var myValue = (!IsPostBack)
    ? null
    : this.Request.Form["myHiddenField"];
Answer

what I did is save the javaScript variable in a cookie and then read it from C#.

JavaScript Code:

<script>
$(document).ready(function () {
   createCookie("height", $(window).height(), "10");
 });

 function createCookie(name, value, days) {
   var expires;
   if (days) {
     var date = new Date();
     date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
     expires = "; expires=" + date.toGMTString();
   } else {
     expires = "";
   }
   document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
  }
</script>  

C# Code:

height of browser:@Request.Cookies["height"].Value;   

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.