简体   繁体   中英

Call C# method from Javascript

if(httpRequest.readyState == 4 && httpRequest.status == 200)
{
    <% SetText(); %>
}

I need to call method from code behind in javascript. Method is obviously called SetText() and it's void.

This I tried didn't work.

You have to expose the C# method using a service or a handler. Depending on your architecture the handler can be implemented in different ways (MVC, .net HttpHandler, JayRock handler, etc.). And then you have to call the method from Javascript using an AJAX request.

And remember, avoid to embed CSharp code blocks inside server side generated Javascript code.

References:

It is not possible, at least if you don't make an AJAX request. Otherwise, it's impossible to access server-side methods via client-side(in this case via JS).

H i answered a similar question on Calling a C# method from Javascript I provided an example using AJAX: Call C# method in javascript function directly

Hope this will help.

The client is incapable of accessing server methods in the manner in which you specified in your question. What you want to do is not possible unless you use something like AJAX.

Please explain what you're trying to do, perhaps someone can explain a different way to solve your problem.

Make one ajax call, there you check whether the connection is ok or not. If connection is ok make the actual call there itself(in server side) and return data.

Since you made an async request you page data is not going to show any error message. Even if there is some error you will get in error handler and you know what to do when error occur.

There should not be any scenario when the client code has to contact server method directly. You can always do work around with that in case your design is like that.

You can accomplish this using AJAX.

I'm currently using a HTTPHandler to make my calls via AJAX. I'm accessing my handler using a service ".asmx" with code the looks like this

<%@ WebService Language="C#" Class="MyClass" %>

try this link http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/calling-an-Asp-Net-C-Sharp-method-web-method-using-javascript/

yes but it is not possible without ajax call :(.

And please make sure you have imported all the necessary jquery files and the function that you have written for ajax call should be a "STATIC".

rest will be cleared please follow the link

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