Zawar Zawar - 1 year ago 66
ASP.NET (C#) Question

How to pass a string from javascript to server? and then get a return value from server in webforms

I have this modal. inside a form tag

<div id="Incoming_Call" class="modal fade" role="document">
<asp:Label runat="server" id="Caller_id" Text="Incoming Call"</asp:Label>

I want to change the label text when the modal will show

string id = "temporary value"//javascript has this value on clientside.
// i don't have this value on page load but after some event triggers.

$('#Incoming_call').on('shown', function(){
var text = '<%= generatestring(id)%>';
$('#<%=Caller_id.ClientID%>').html = id;

I need to send that
variable to server side to a function
after the string has changed from
id="temporary Value"
or something

This is on server side.

public string generateString(string id)
id = // does some processing;
return id;

So, I want to send a variable of javascript to the server side then server has to do some processing and return the value. the javascript variable is not ready at page load time. So I can't pass it inside
these tags and get a newer value. It will only pass "temporary value" as a string not the new value.

Answer Source

Calling a server side method from javascript is really simple.You can do this with jQuery $.ajax function and a [WebMethod]

Code behind:

protected void Page_Load(object sender, EventArgs e)

public static string generateString(string id)
    return String.Format("Response from server for - {0}.Call time - {1}",id,DateTime.Now.ToString("HH:mm:ss"));


<head runat="server">
    <script src=""></script>
    <script type="text/javascript">
        $(function () {
            var id = "temporary value";

            $("#btnMakeAjaxCall").click(function () {

            function MakeAjaxCall() {
                    type: "POST",
                    url: "AjaxCallExample.aspx/generateString",
                    contentType: "application/json;charset=utf-8",
                    data: '{id:"' + id + '"}',
                    dataType: "json",
                    success: function (data) {
                        var caller = '<%: Caller_id.ClientID %>';
                        $("#" + caller).text(data.d)
                    error: function (errordata) {
    <form id="form1" runat="server">
        <input type="button" id="btnMakeAjaxCall" value="Make AJAX call" />
        <asp:Label ID="Caller_id" runat="server" Text="Incoming Call"></asp:Label>