.aspx页面 用html按钮传送数据到 .aspx.cs后台的和“利用Ajax连接aspx与aspx.cs”方法记录

  想了想,一般上课老师都是直接用的asp:Button控件来直接实现了按钮和后台监控事件的响应,如果不用asp:Button,用html的button元素,可不可以实现一样的功能呢?

暂时只找到一个解决办法:利用Ajax

 .aspx部分

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>[Ajax测试]</title>
    <script type="text/javascript" src="Content/jquery-3.0.0.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax({
                    type: "post",//Must be POST
                    contentType: "application/json",//Must
                    data: "{'name':'xtyang','age':23}",//Response to parameters of method getReturn
                    url: "TestAjax.aspx/getReturn",
                    success: function (result) {
                        alert(result.d);//Must
                    }
                });
            });
            $(".Input").blur(function () {
                $.ajax({
                    type: "POST",
                    url: "TestAjax.aspx/getCount",
                    contentType: "application/json",
                    data: "{'str':'" + $('.Input').val() + "'}",//notice "'"
                    success: function (result) {
                        $('.ret-i').html("");//set the content with empty content
                        $('.ret-i').html(result.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <button id="ajax">Test</button>
            <input type="text" class="Input" />
            <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
        </div>
        <div class="ret-i">
        </div>
    </form>
</body>
</html>

  对应的.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;
using System.Web.Services;  //Must

namespace xxxxxx
{
    public partial class TestAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        [WebMethod]
        public static string getReturn(string name, string age)    //Must
        {
            TestAjax tt = new TestAjax();
            return name + " is " + age.ToString() + " years old";
            // return "1";
        }

        [WebMethod]
        public static string getCount(string str)
        {
            if (str.Length < 6)
                return "Input is not valid";
            else
                return "Input is valid";
        }
    }
}
原文地址:https://www.cnblogs.com/Damocles-Sword/p/13191286.html