简体   繁体   中英

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

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;
    }
}

The code you are showing is executed server side when the HTML is generated. In other words it is executed BEFORE it hits the browser and your user had a chance to do anything with the page.

No matter what syntax you would use here the information you want cannot be accessed at this time - it does not exist yet.

The right approach here is to sent this information to the server either by posting the page or using AJAX and then, on the tail end of request/response cycle do your processing

Another option would be to do the processing client side using Javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM