Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Calling C# from JavaScript
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));
}
});
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 } };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.