How should data be passed between client-side Javascript and C# code behind an ASP.NET app?

  • 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 don't feel complete. Is there a more standard way of passing data between client side JavaScript and C# back-end code?

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

    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.

    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.

    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.

    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.

  • 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" 
    EnablePartialRendering="true" runat="server" />

    Code-behind Code

    using System.Web.Services;
    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.

    Great example, this works well and I will be using it. Thanks!

  • 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 and receives the data from the server in the supplied function.

        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

    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.

  • 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"]);

    * 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.

    I'm pretty sure there's a special place in hell for people who string build JavaScript snippets on the server like that

    @Raynos There is nothing wrong with generating JavaScript server side.

    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.


  • 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.

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


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

    asp control:

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

    to get the values on postback


    If its, asp control hidden input, you can use


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

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM

Tags used