Butters Butters - 13 days ago 5
C# Question

Call C# method from JavaScript with parameter

I want to call a C# method with parameter from JavaScript. It is possible, if I remove the parameter

of the method
<% showDetail(); %>

function showDetail(kurz)
String s = kurz.toString();
<% showDetail(s); %>;

C# methods to test:

public void showDetail(String s)
Label_Test.Text = s.ToString();
public void showDetail()
Label_Test.Text = "";

It works fine without parameter but with
variable I get a compiler error:

CS0103: The name 's' does not exist in the current context

I have tried

showDetail(Object s){....}

and also

showDetail(String s){....}

but it does not work.


Create a web method. That's an easy and neat way of calling c# methods from Javascript. You can call that method using jQuery Ajax. See the below example for a webMethod.

public static string RegisterUser(string s)
    //do your stuff
    return stringResult;

and then call this method using jQuery ajax. You can pass parameters also. like given below

function showDetail(kurz) { 
String sParam = kurz.toString(); 
    type: "POST", 
    url: "PageName.aspx/MethodName", 
    data: "{s:sParam}", // passing the parameter 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function(retValue) {
        // Do something with the return value from.Net method