Search code examples
c#javascripthtmlanchorservertag

Pass a parameter to server method using JavaScript


I have a public in my code behind page that takes a string. I would like to call this method from javascript.

The parameter that I want to pass down is variable that changes from a ddl.

So I have something like this:

 var value = document.getElementById('ddlContact').value;
        <%=PopulateContactFields("value") %>

This passes down the word 'value' and not the data in value.

I can't figure out the proper syntax to pass down the data in value.

Thanks


Solution

  • As mentioned by others, trying to access C# code behind directly from javascript is impossible.

    However, you can communicate with it indirectly.

    I think your best shot is to use a combination of jQuery and the [WebMethod] attribute.

    javascript function using jQuery to do an AJAX call:

    function Search() {
        var search = $('#<%= ddlContact.ClientId %>').val();
        var options = {
            type: "POST",
            url: "Default.aspx/Hello",
            data: "{'name' :'" + search + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                alert(msg);
            }
        };
        $.ajax(options);
    }
    

    Code behind:

    public partial class _Default : System.Web.UI.Page
    {
        [WebMethod]
        public void Hello(string name)
        {
          return "Hi " + name;
        }
    }