0

I tried to call c# function in javascript so i used this: var a = <%=MYC#FUNCTION()%>, but the function in the weird brackets execute even before my page load. like executing the function is the top priority of my code. i want the function to execute when i am calling it in my javascript code. Please help me, i need this for my project in school. i tried to use this but i didnt really understood this ->

<script type="text/javascript">             //Default.aspx
   function DeleteKartItems() {     
         $.ajax({
         type: "POST",
         url: 'Default.aspx/DeleteItem',
         data: "",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
             $("#divResult").html("success");
         },
         error: function (e) {
             $("#divResult").html("Something Wrong.");
         }
     });
   }
</script>

[WebMethod]                                 //Default.aspx.cs
public static void DeleteItem()
{
    //Your Logic
}
4
  • When do you want it to execute? After page load or on click? Commented Mar 22, 2020 at 11:36
  • That is executing server-side, not on the page in the browser. Commented Mar 22, 2020 at 11:37
  • i want the function to execute when i am calling it in my javascript code. Commented Mar 22, 2020 at 12:00
  • If you want to call C# from JavaScript in your browser, you have to make an AJAX call. The C# can only run on the server. (That said, Blazor will let you run C# on the browser, but that's a whole other technology.) Commented Mar 22, 2020 at 12:05

1 Answer 1

1

You are misunderstanding the life cycle of the request/response. In your code, the order of execution will be

  1. Web browser sends a request to your web server.
  2. Web server (C# code) now handles the request and start creating HTML response.
  3. Web server uses your controller/view (MVC) or .aspx/.aspx.cs (web form) to create the response.
  4. Your code "MYC#FUNCTION()" is now executed. Let assume it returns a number 123.
  5. After this, your html response is sent back to web browser.
  6. Web browser receives the response and display to UI. Now, if you inspect HTML you will see "var a = 123;" (123 coming from your "MYC#FUNCTION()")

If you want to execute "MYC#FUNCTION()" after page load. Then you need to look at AJAX.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.