Home > OS >  How can I perform an ajax call to .aspx.cs
How can I perform an ajax call to .aspx.cs

Time:10-11

I've spent 4 days trying to make an ajax call to my .aspx.cs. In the best case, I got answer in html format. I don't understand why that happened, maybe I have to add some lib from NuGet or write something in web.config? What I tried:

  • [HttpPost] [HttpGet]
  • [WebMethod]
  • jQuery ajax call
  • change url
  • my first app was a sample from VS with razor pages, I thought the problem was in using razor, so I created new project - a empty web application, but I still got the same answer from server in html format.

What I want to get: My app imitates a vending machine. A user click on buttons with coins and coins have to increase on server side. (BtnAddCoin()) Also user's coins are always showing on a panel. (ShowInsertedCoins())

ClientSide.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ClientSide.aspx.cs" Inherits="VendingMachine.ClientSide" Async="true" AsyncTimeout="60"  %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <link rel="stylesheet" href="StyleSheet.css" />
    <title></title>
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">


    function AddCoin(coin) {
        alert(coin);
        var val1 = coin;

        $.ajax({
            type: "POST",
            url: "/ClientSide.aspx/BtnAddCoin",
            data: '{coin: "'   coin   '" }',
            dataType: "text",
            success: function (data) {
                alert("AddCoin"   data);

            },
            error: function (req, status, error) {
                alert(error   status);
            }
        }).done(function (result) { ShowInsertedCoin(); });

    }

    function ShowInsertedCoin() {
        var insertedCoins = document.getElementById('InsertedCoins');
        alert('ShowInsertedCoin');
        $.ajax({
            type: "GET",
            url: "/ClientSide.aspx/ShowInsertedCoins",  
            dataType: "text",
            data: {}, 
            success: function (data) {  
                alert("ShowInsertedCoin "   data);
                insertedCoins.textContent = data;
            }
        });
    }
   
</script>
</head>
<body>
    <form id="form1" runat="server">     
    </form>

     <div>
        <h1>Coffee machine</h1>
     </div>
    <div> 
        <div>
                <p> Add coins: </p>           
            <div>                
                <div>          
                         <a id ="coin1" onclick="AddCoin(1)"> 1 </a>
                         <a> 2 </a>
                         <a> 5 </a>
                         <a> 10 </a>
                     </div>
                </div>
            <div>
                <p id="InsertedCoins" ><%=ShowInsertedCoins()%> </p>
            </div>
            </div>  
    </div>
</body>
</html>

ClientSide.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace VendingMachine
    {
    public partial class ClientSide : System.Web.UI.Page
    {     
        static int coins = 10;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string ShowInsertedCoins()
        {
            return "You inserted: "   coins.ToString();
        }

        [WebMethod]
        public void BtnAddCoin(int coin)
        {
            coins =  coin;
            //ShowInsertedCoins();
        }         
    }
}

So, how I can do an ajax call to .aspx.cs with jQuery or js? Why do I get html format when my function has to return a string? Thanks for your attention and help.

CodePudding user response:

As other persons already commented, it's recommended to use newer technollogies, other than Webforms, but if you wan't to continue using it or it's an project of your work or something related, here's how i normally do in Javascript:

$.ajax({
            method: "POST",
            url: "ClientSide.aspx/BtnAddCoin",
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify({
                obj: JSON.stringify(data)
            }),
            success: function (response) {
                let return = JSON.stringify(response.d);
                // something
            },
            error: function (ex) {
                // something
                console.log(ex.Message)
            },
            beforeSend: function () {
                // something
            },
            complete: function () {
                // somethin
            }
        });

And for the C# file, every time you want to make an webmethod, that method need to be public and static, just like that (At least i learned that every time needs to be static):

[WebMethod]
public static string BtnAddCoin(int newCoin)
{
    return newCoin;
}

Try and see if that helps

CodePudding user response:

Lots of issues here.

First issue?

You have this static value for the page class:

static int coins = 10;

You can't really control, or use or have static values in a class. The MAIN reason is such values will apply to all users of the site - not just the one user.

You can as a general rule call, use, consume static classes. In fact in vb.net, we OFTEN create a Module, and inside we have our boatload of helper routines, and routines that we freely call that library of code. While each of the routines can freely use local values, you can NOT use variables global to that module, since no instance of the class is being created, and as a result, multiple users will/would be able to set such values - and overwrite values used by other users. Worse yet, how long does the server persist such static values?

Answer: it is a total Las Vegas gamble.

this means to persist that coin count, we can choose one of MANY possible ways to persist that value.

We can have a global JavaScript variable hold the value.

We can use a control like text box to hold the value (and hide it)

We can use a hidden control (so ViewState will hold the value).

We can use ViewState directly to the hold the value (client side persisting), but is managed by server side code.

We can use session() to hold the value (server side persisting)

Over the years, we see "many" attempts to pass, share, persist data vales in a static class. It sometimes works, and often during development it "seems" to work, but the instant you deploy to a real working site, it blows up in a huge ball of flames.

So, using a static class to hold a Hodge podge of code? Sure, no problem, and that's quite much what we do in c# to obtain general "code module" of routines that we need throughout the applcation. But, be a vb.net module, or in c# a static class? Any concept of global values to that static class MUST be taken off the table and NOT used!!

Ok, so let's cook up a working example. We first have to choose a place/spot to hold and persist our coin count.

Hum, we have many choices. However, since this example code involves server side code. Then let's use session.

I mean, it would kind of defeat this whole example if we write the code 100% client-side JavaScript (which is not all that bad of a idea). However, since we attempting to learn, and use a web method?

Then let's wire this up using a web method. (as noted, we really don't need to use any server-side code here).

So, if we going to use session() to persist the value, then on first page load, we setup our coin count with a starting value of 10.

Also, WHEN you use/call/consume a web method of the page? There is NOT a instance of the page class. As a result, ANY AND ALL web methods must be static. In fact, it means really don't care if we placed the web method in the current page, is some ascx file, or wherever. Since the web page is NOT being posted back to the server, then all of the controls, values and things on that web page are STILL sitting on your desktop, and there is no copy of the web page in existence on the server side.

Next up:

     data: '{coin: "'   coin   '" }',
        dataType: "text",

So, you have some jason data, yet on the next line you saying we going to use text? Nope!!! If you going to pass json data the method, it going to return such json data back. Same goes if you choose xml, or whatever.

So, you can't pass json data, but then on the next line state we going to use text!!!!!

Ok, so our server side code now becomes this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // setup starting coin count 
            Session["CoinCount"] = (int)0;
        }
    }

    [WebMethod(enableSession: true)]
    public static void BtnAddCoin(int coin)
    {

        int MyCoins = (int)HttpContext.Current.Session["CoinCount"];
        MyCoins  = coin;
        HttpContext.Current.Session["CoinCount"] = MyCoins;    
        Debug.Print("coins = "   MyCoins.ToString());
        
    }

    [WebMethod(enableSession: true)]
    public static string ShowInsertedCoins()
    {
        int MyCoins = (int)HttpContext.Current.Session["CoinCount"];
        return "You inserted: "   MyCoins.ToString();
    }

Now, for client side, DO NOTE that when you use json format, then the return value/results are of the ".d" property of the web method. This is a asp.net thing, and it just the way it works.

So, now our client side code;

    <div>
        <div>
            <p>Add coins: </p>
            <div>
                <div>
                    <a id="coin1" onclick="AddCoin(1)">1 </a>
                    <a>2 </a>
                    <a>5 </a>
                    <a>10 </a>
                </div>
            </div>
            <div>
                <p id="InsertedCoins"></p>
            </div>
        </div>
    </div>

    <script>


        function AddCoin(coin) {
            $.ajax({
                type: "POST",
                url: "/CoinCount.aspx/BtnAddCoin",
                data: JSON.stringify({ coin: coin }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    // alert("AddCoin"   data);
                    ShowInsertedCoin();
                },
                error: function (req, status, error) {
                    alert("x"   error   status);
                }
            }).done(function (result) { ShowInsertedCoin(); });

        }

        function ShowInsertedCoin() {
            var insertedCoins = $('#InsertedCoins');
            $.ajax({
                type: "POST",
                url: "CoinCount.aspx/ShowInsertedCoins",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: {},
                success: function (data) {
                    insertedCoins.text(data.d);
                }
            });
        }

    </script>

Next up?

How did "form2" get inserted into this page?

If you create a new aspx page, (web forms), then the last gazillion pages will have by default form1, and BIG flag that you have form2 here.

Anyway, the above should work. Note that you not only are sending json data, but you as a general rule need to add the content type, and you had this missing:

 contentType: "application/json; charset=utf-8",

Also, so far we only added a click event for the "1", and you have to do the same for the other 3 values you have.

  • Related