Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm looking for the most efficient / standard way of passing data between client-side Javascript code and C# code behind an ASP.NET application. I've been using the following methods to achieve this but they all feel a bit of a fudge.

To pass data from Javascript to the C# code is by setting hidden ASP variables and triggering a postback:

<asp:HiddenField ID="RandomList" runat="server" />

function SetDataField(data) {
      document.getElementById('<%=RandomList.ClientID%>').value = data;
}

Then in the C# code I collect the list:

protected void GetData(object sender, EventArgs e)
{
      var _list = RandomList.value;
}

Going back the other way I often use either ScriptManager to register a function and pass it data during Page_Load:

ScriptManager.RegisterStartupScript(this.GetType(), "Set","get("Test();",true);

or I add attributes to controls before a post back or during the initialization or pre-rendering stages:

Btn.Attributes.Add("onclick", "DisplayMessage("Hello");");

These methods have served me well and do the job, but they just dont feel complete. Is there a more standard way of passing data between client side Javascript and C# backend code?

Ive seen some posts like this one that describe HtmlElement class; is this something I should look into?

share|improve this question
5  
json.org –  Oded Nov 29 '11 at 17:29
    
It kind of depends on what you mean by passing data between server and client. If the data is known at the point the page is rendered then adding a script to create your data or setting json via a literal or similar or other variation are perfectly reasonable. If, OTOH, you're trying to have a page that interacts with the server without doing a postback then that's an entirely different problem. Definitely look at json. –  Murph Nov 29 '11 at 21:41
    
For example. If i launched a button from the client that got some data from an xml file. Then some calculations are done on the data in C#. Then i want that finished result displayed in a pretty javascript graphical display. Thats one postback where the client does not know the result until after the postback has been raised. –  ctck Nov 29 '11 at 22:46
    
From that comment you're still able to perform all the work at the server - load/process/return - so, in the first instance, I'd do just that. Format the data as json, include the json when you render the page (a literal will let you do this). When you get that to work you probably then want to do something more asynchronous - but it will be the same json. –  Murph Nov 30 '11 at 20:40
    
Thanks all. After reading the advice here and doing some extra research i have found a new method of achieving what i wanted to do. The main issue i was getting was that when i performed an Ajax post i couldn't get the client side code to remember where the program was at. Im now using JQuery $Ajax.Post as it gives a on Success post back to the client saving session data. –  ctck Jan 16 '12 at 22:23
add comment

6 Answers

You can simply and easily call a static page method from JavaScript like in this example. If you need to call the method from multiple pages, you can setup a web service and call it from Javascript the same way. Example also included below.

.aspx Code

<asp:ScriptManager ID="ScriptManager1" 
EnablePageMethods="true" 
EnablePartialRendering="true" runat="server" />

Code-behind Code

using System.Web.Services;

[WebMethod]
public static string MyMethod(string name)
{
    return "Hello " + name;
}

Javascript Code

function test() {
    alert(PageMethods.MyMethod("Paul Hayman"));
}

NOTE: The page methods have to be static. This could be problematic for you, depending on what the application is trying to do. However, if the information is based on session at all, and you're using some sort of built-in authentication, you can put an EnableSession attribute on the WebMethod decorator, and that will allow you to get at HttpContext.Current.User, Session, etc.

share|improve this answer
    
Great example, this works well and I will be using it. Thanks! –  Mausimo Jun 11 '12 at 22:23
add comment

I'd recommend having a look at jQuery. JQuery can be used to make AJAX calls back to the server, which can data back in whatever format you need - a good format could be JSON, since it can be used directly in javascript.

To pull data from the server down to javascript using jQuery, the following fetches makes an asynchronous request to http://youserver.com/my/uri and receives the data from the server in the supplied function.

$.get("my/uri", 
    function(data) { 
       // client side logic using the data from the server
    })

Sending data from javascript to the server works similarly:

$.post("my/uri", { aValue : "put any data for the server here" }
    function(data) { 
       // client side logic using the data returned from the server
    })
share|improve this answer
    
Thanks, this is great, but im specifically referring to situations where a postback is done prior to the client knowing what to display. If the "result" is achieved through c# how do i then "inject" it back to the client. –  ctck Nov 29 '11 at 22:51
add comment

Microsoft have implimented the UpdatePanel control to do ajax so that is arguably the "standard" way. I wouldn't personally recommend using it though, it has nowhere near the rich feature set and control you have when using JavaScript directly.

This is the way I personally do it:

Create hidden fields for any client side values you want to use in a standard page postback (ie when user hits submit)

<asp:HiddenField ID="selectedProduct" runat="server" />

In the code behind register the controls you want to use client side.

    /* Register the controls we want to use client side */

    string js = "var productBox = document.getElementById('" + selectedProduct.ClientID + "'); ";
    js += "var macCodeBoxBE = document.getElementById('" + beMacCode.ClientID + "'); ";


    ClientScript.RegisterStartupScript(this.GetType(), "prodBox", js, true);

Use a javascript library* to do your ajax post/get then use JavaScript to update the page based on the response

$.get("../ajax/BTBookAppointment.aspx?dsl=" + telNumberBox.value + "&date=" + requiredDate.value + "&timeslot=" + ddTimeslot.value, function (response, status, xhr) {

    if (response.indexOf("not available") > -1) {
        loaderImage.src = "../images/cross.png"
        output.innerHTML = response;
    } });

Write a seprate "ajax" page that overrides the render method to do the work.

protected override void Render(HtmlTextWriter writer)
{
    if (string.IsNullOrEmpty(Request["mac"])) { return; }
    if (string.IsNullOrEmpty(Request["dsl"])) { return; }
    DataLayer.Checkers.BTmacCheckResponse rsp = DataLayer.Checkers.Foo.CheckMAC(Request["dsl"], Request["mac"]);

    writer.Write(rsp.Valid.ToString());
}

* There are plenty of libraries to choose from, you can even roll your own. I would recomend jQuery, its stable and has an extensive feature set.

share|improve this answer
7  
I'm pretty sure there's a special place in hell for people who string build JavaScript snippets on the server like that –  Raynos Nov 30 '11 at 13:03
1  
@Raynos There is nothing wrong with generating JavaScript server side. –  Tom Squires Nov 30 '11 at 13:53
2  
if you want the server to do anything, you send a HTTP request (using XHR) to a sensible URI with sensible data. From there on the HTTP server will know what to do with it. –  Raynos Nov 30 '11 at 13:56
add comment

To set a input tag that doesn't need serverside asp, you can use: (or <%# %> for forms databinding)

html:

<input type="hidden" value='<%= RandomValues %>' name="RANDOM_VALUES" />

asp control:

<asp:HiddenField ID="RandomList" runat="server" />

to get the values on postback

Request.Form["RANDOM_VALUES"]

If its, asp control hidden input, you can use

Request.Form[RandomList.UniqueID]

The neat part about Request.Form is if you have multiple tags with the same "name" attribute, it will return the result in CSV.

share|improve this answer
add comment

JSON is the best practice way to accomplish the task. Do not look at the problem as a passing between "C# and JavaScript". This way of thinking leads to code oddities such as what you have in the original post.

More generally, it's just passing objects between the client and the server in a language agnostic fashion. JSON is great for the task because it's widely supported and easy to read.

share|improve this answer
add comment

Think Object Oriented

Take some time to do some good business model/data analysis and get things into coherent objects. In generic OO terms you can do basically any inheritance and polymorphic thing you need. JavaScript syntax being so different you probably need to force yourself to think in terms of abstract base classes, virtual methods, etc. I can imagine a class with a "virtual" method for mapping a data structure to an html element.

Oh, and JSON to structure your data - ideally making it map structurally to the data on the C# side.

Structure is everything. Structured data leads to structured objective ways of handing it which leads to structured implementation which eliminates that fudge-y feeling.

share|improve this answer
    
I'm sure there are questions about how to structure data, but this is not one of them. –  philw Jul 24 '13 at 9:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.