Calling C# from JavaScript

Suppose you need to treat a jQuery object from Javascript and from there you want to invoke (without a full postback) a C# async in a Web Forms Page function, which is not a WebMethod!

javascript

We can use the usual Ajax plus the following code-behind


function runAsync() {
$.ajax({
type: "POST",
url: "PageAjax2.aspx",
async: true,
//data: JSON.stringify( { msg1:"one", msg2:"two", method:"Test" }),
//contentType: "application/json; charset=utf-8",
data: { msg1:"one", msg2:"two", method:"Test" },
dataType: "json",
success: function (resp) {
alert('OK: ' + JSON.stringify(resp));
},
error: function (e) {
alert('Error: ' + JSON.stringify(e));
}
});

view raw

jquery.js

hosted with ❤ by GitHub


protected async void Page_Load(object sender, EventArgs e)
{
test++;
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "Test")
{
MyType[] obj = await Test(Request.Form["msg1"], Request.Form["msg2"]);
string json = new JavaScriptSerializer().Serialize(obj);
Response.Write(json);
Response.ContentType= "application/json; charset=utf-8";
Response.Flush();
Response.End();
return;
}
}
}
public async Task<MyType[]> Test(string msg1, string msg2)
{
await Task.Delay(2000); // no .ConfigureAwait(false) needed!
Label1.Text = msg1;
Label2.Text = msg2;
return new MyType[2] { new MyType { Message = msg1 }, new MyType { Message = msg2 } };
}

view raw

PageAjax2.aspx

hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s