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

asp.netcjavascriptnetweb-development

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?

Best Answer

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.

Related Topic