Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 s 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 s 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.

like image 752
Butters Avatar asked Sep 04 '13 09:09

Butters


People also ask

What is call in C?

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.

Is call by value in C?

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C programming uses call by value to pass arguments.

Can you call C from C++?

Just declare the C function extern "C" (in your C++ code) and call it (from your C or C++ code). For example: // C++ code. extern "C" void f(int); // one way.

What is function call in C with example?

During a function call, a function may accept one or more inputs as arguments, process them and return the result to the calling program. For example, in function call sqrt (x), the sqrt function accepts the value of x as input and returns its square root.


1 Answers

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.

[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(); 
    $.ajax({ 
    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
        } 
    }); 
} 
like image 155
Varun Paul Avatar answered Sep 30 '22 03:09

Varun Paul