asp.net 调用jquery ajax

转载 2012年04月10日 08:54:58

AjaxTest.aspx:

<!--

    注意使用1.6和1.7的版本的Jquery时调用远程Web Service失败,1.3和1.4的时候远程调用成功,所以调用1.4的版本
-->

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxTest.aspx.cs" Inherits="POCWBS.HTML5.AjaxTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Templates</title>
   <script type="text/html" id="personTemplate">
       <div>
            <div style="float:left;"> ID : </div> <div>${UId} </div> 
            <div style="float:left"> Name : </div> <div>${Name} </div> 
            <div style="float:left"> Address : </div> <div>${Address} </div> <br />
       </div>
   </script>

    <!--<script src="../Js/jquery-1.7.2.min.js" type="text/javascript"></script>-->
    <!--
    jquery download address
    http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
    -->
    <script src="../Js/jquery-1.4.2.min.js" type="text/javascript"></script>    
    <script type="text/javascript" language="javascript">

       var personCount;
       $(document).ready(function() {
           PopulatePersons();
           PopulateEmployees();
           PopulateLocalServiceUsers();
           PopulateRemoteServiceUsers();
           CheckValidUser("487464","1");
       });


   
 function PopulatePersons(op) {
             $.ajax({
                 type: "POST",
                 url: "AjaxTest.aspx/GetPersons",
                 contentType: "application/json; charset=utf-8",
                 data: "{}",
                 dataType: "json",
                 success: PersonAjaxSucceeded,
                 error: PersonAjaxFailed
             }); 
         }
        function PersonAjaxSucceeded(result) {
            alert('Person success');
            //DisplayChildren(result);
        }
        function PersonAjaxFailed(result) {
            alert('Person failure');
            alert(result);
        }

        function DisplayChildren(result) {

            var persons = eval(result.d);
            personCount = persons.length;
                $("#personTemplate").tmpl(persons).appendTo($("#divPerson"));
        }
        function AddPerson() {
            var inputs = new Object();
            inputs.count = ++personCount;

            $.ajax({
                type: "POST",
                url: "AjaxTest.aspx/AddPerson",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(inputs),
                dataType: "json",
                success: PersonAjaxSucceeded,
                error: PersonAjaxFailed
            });         
        } 
        
        
         function PopulateEmployees() {
             $.ajax({
                 type: "POST",
                 url: "AjaxLogic.aspx/GetEmployees",
                 contentType: "application/json; charset=utf-8",
                 data: "{}",
                 dataType: "json",
                 success: EmployeeAjaxSucceeded,
                 error: EmployeeAjaxFailed
             }); 
         }
         
         function EmployeeAjaxSucceeded(result) {
             alert('Employee success');
            //DisplayChildren(result);
         }
         function EmployeeAjaxFailed(result) {
            alert('Employee failure');
            alert(result);
         }
         
         
         function PopulateLocalServiceUsers() {
             $.ajax({
                 type: "POST",
                 url: "ajaxWebService.asmx/HelloWorld",
                 contentType: "application/json; charset=utf-8",
                 data: "{}",
                 dataType: "json",
                 success: LocalUserAjaxSucceeded,
                 error: LocalUserAjaxFailed
             });            
         }
         
         function LocalUserAjaxSucceeded(result) {
            alert('Local User success');
        }
        function LocalUserAjaxFailed(result) {
            alert('Local User failure');
        }


        var WebServiceURL = "http://localhost/POCWBSWebService/";
        function PopulateRemoteServiceUsers() {
             $.ajax({
                 type: "POST",
                 url: WebServiceURL + "WebService1.asmx/HelloWorld",
                 contentType: "application/json; charset=utf-8",
                 data: "{}",
                 dataType: "json",
                 success: RemoteUserAjaxSucceeded,
                 error: RemoteUserAjaxFailed
             });            
         }
         
        function RemoteUserAjaxSucceeded(result) {
            alert('Remote User success');
        }
        function RemoteUserAjaxFailed(result) {
            alert('Remote User failure');
        }
        
        function CheckValidUser(globalID,password)
        {        
//            var inputs = new Object();
//            inputs.globalID = globalID;
//            inputs.password = password;

//            $.ajax({
//                type: "POST",
//                url: "UserService.asmx/CheckValidUser",
//                contentType: "application/json; charset=utf-8",
//                data: JSON.stringify(inputs),
//                dataType: "json",
//                success: CheckUserAjaxSucceeded,
//                error: CheckUserAjaxFailed
//            });  
        
//            $.ajax({
//                 type: "POST",
//                 url: "UserService.asmx/CheckValidUser",
//                 contentType: "application/json; charset=utf-8",
//                 data:"{'globalID':'487464','password':'1'}",
//                 dataType: "json",
//                 success: CheckUserAjaxSucceeded,
//                 error: CheckUserAjaxFailed
//             });       

            $.ajax({
                 type: "POST",
                 url: WebServiceURL + "UserService.asmx/CheckValidUser",
                 contentType: "application/json; charset=utf-8",
                 data:"{'globalID':'487464','password':'1'}",
                 dataType: "json",
                 success: CheckUserAjaxSucceeded,
                 error: CheckUserAjaxFailed
             });                
         }
         
         function CheckUserAjaxSucceeded(result) 
         {
            alert('Check User success');
            alert(result.d);
         }
         
         function CheckUserAjaxFailed(result) 
         {            
            alert('Check User failure');
            alert(result.responseText);
            alert(result.status);
            alert(result.statusText);
            
         }

   </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    <table>
    <tr><td><input id="Button1" type="button" value="AddMorePerson" onclick="AddPerson();"/></td></tr>
    <tr><td>
    
        <div id="divPerson" style="font-family:Verdana; font-size:12px;">
            
        
        </div>
    </td></tr>
        
    </table>
       <asp:HiddenField ID="hfPersonData" runat="server" />      
    </div>
    </form>
</body>
</html>



AjaxTest.aspx.cs:

using System;
using System.Web.Services;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data.OleDb;
using System.Data;



namespace POCWBS.HTML5
{
    public partial class AjaxTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod()]
        public static string GetPersons()
        {
            List<Person> persons = new List<Person>()
            {
                new Person { UId = 1, Name = "Brij", Address = "Noida"},
                new Person { UId = 2, Name = "Rahul", Address = "New Delhi" },
                new Person { UId = 3, Name = "John0", Address = "Chris"}
            };

            JavaScriptSerializer ser = new JavaScriptSerializer();
            // ser.Serialize(persons);
            return ser.Serialize(persons);

        }
        [WebMethod()]
        public static string AddPerson(string count)
        {

            List<Person> persons = new List<Person>()
            {
                new Person() { UId = Convert.ToInt32(count), Name = "New Name" + count, Address = "My New Address" + count }
            };

            JavaScriptSerializer ser = new JavaScriptSerializer();
            // ser.Serialize(persons);
            return ser.Serialize(persons);

        }
    }

    public class Person
    {
        public int UId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }
}



本地工程页面文件 AjaxLogic.aspx.cs

using System;
using System.Web.Services;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace POCWBS.HTML5
{
    public partial class AjaxLogic : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod()]
        public static string GetEmployees()
        {
            List<Employee> persons = new List<Employee>()
        {
            new Employee { EmployeeId = 1000, Age=34, Name ="Rahul", 
                Adresses = new List<Address>()},
            new Employee { EmployeeId = 1001, Age=29, Name ="Atul", 
                Adresses = new List<Address>()},
            new Employee { EmployeeId = 1002, Age=32, Name ="Rohan", 
                Adresses = new List<Address>()}

        };
            persons[0].Adresses.Add(new Address() { Street = "Street 5", AddressLine1 = "New Bay Area", AddressLine2 = "Near Roma Hospital", City = "Kolkata", Zip = "221001" });
            persons[0].Adresses.Add(new Address() { Street = "Bahadur marg", AddressLine1 = "Kailash Colony", AddressLine2 = "Near Public School", City = "Lucknow", Zip = "226001" });
            persons[0].Adresses.Add(new Address() { Street = "Ali Crossing", AddressLine1 = "Republic Colony", AddressLine2 = "Silk Garden", City = "Ahamedabad", Zip = "221021" });

            persons[1].Adresses.Add(new Address() { Street = "Street No 2", AddressLine1 = "Pocket Gama", AddressLine2 = "Near Appollo Hospital", City = "G Noida", Zip = "201301" });
            persons[1].Adresses.Add(new Address() { Street = "1634", AddressLine1 = "Sector 15", AddressLine2 = "Near Nirulas", City = "Noida", Zip = "201301" });

            persons[2].Adresses.Add(new Address() { Street = "Street 10", AddressLine1 = "Sector 18", AddressLine2 = "Near Mosaic", City = "Noida", Zip = "201301" });
            persons[2].Adresses.Add(new Address() { Street = "Gol Marg", AddressLine1 = "New Era Colony", AddressLine2 = "Pitambaram", City = "Alllahabad", Zip = "221001" });

            JavaScriptSerializer ser = new JavaScriptSerializer();
            // ser.Serialize(persons);
            return ser.Serialize(persons);
        }

    }


    public class Employee
    {

        public int EmployeeId { get; set; }
        public String Name { get; set; }
        public int Age { get; set; }
        public List<Address> Adresses { get; set; }
    }

    public class Address
    {
        public string Street { get; set; }
        public String AddressLine1 { get; set; }
        public String AddressLine2 { get; set; }
        public string City { get; set; }
        public string Zip { get; set; }
    }

}

本工程内的Web Service 文件ajaxWebService.asmx.cs:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace POCWBS.HTML5
{
    /// <summary>
    /// Summary description for ajaxWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class ajaxWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod()]
        public string GetUsers()
        {
            List<User> users = new List<User>()
            {
                new User { UId = 1, Name = "Brij", Address = "Noida"},
                new User { UId = 2, Name = "Rahul", Address = "New Delhi" },
                new User { UId = 3, Name = "John0", Address = "Chris"}
            };

            JavaScriptSerializer ser = new JavaScriptSerializer();
            return ser.Serialize(users);
        } 
    }

    public class User
    {
        public int UId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    } 
}



其他工程的Web Service文件 UserService.asmx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

using System.Text;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Web.Script.Serialization;


namespace POCWBSWebService
{
    /// <summary>
    /// Summary description for UserService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class UserService : System.Web.Services.WebService
    {

        [WebMethod]
        public string CheckValidUser(string globalID, string password)
        {
            //string sql = "select * from Customers";
            //Database db = DatabaseFactory.CreateDatabase();
            //DataSet ds = db.ExecuteDataSet(CommandType.Text, sql);
            //return ds;
            string _strMsg = "";
            string _strPath = Server.MapPath("Files/Users.xls");
            try
            {
                string conn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source=" + _strPath + ";" +
                "Extended Properties='Excel 8.0;IMEX=1;'";

                string sql = "select * from [Sheet1$] WHERE [GLOBAL_ID]='" + globalID + "' and [PASSWORD]='" + password + "'";
                OleDbCommand cmd = new OleDbCommand(sql, new OleDbConnection(conn));
                OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
                DataSet ds = new DataSet();
                ad.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    _strMsg = "succ";
                }
                else
                {
                    _strMsg = "User does not exist or password is not correct.";
                }
            }
            catch (Exception ex)
            {
                _strMsg = "Exception:" + ex.Message.ToString();
            }
            return _strMsg;
        }


        [WebMethod]
        public string GetDatas(String PA, String PB)
        {
            //return DataTable2Json(CreateDatas(PA, PB));
            return string.Format("{0}、{1}", PA, PB);
        }

        //for test
        private System.Data.DataTable CreateDatas(String PA, String PB)
        {
            System.Data.DataTable DT = new System.Data.DataTable("BlogUser");
            System.Data.DataRow dr;
            DT.Columns.Add(new System.Data.DataColumn("UserId", typeof(System.Int32)));
            DT.Columns.Add(new System.Data.DataColumn("UserName", typeof(System.String)));
            DT.PrimaryKey = new System.Data.DataColumn[] { DT.Columns["UserId"] };

            for (int i = 0; i < 8; i++)
            {
                dr = DT.NewRow();
                dr[0] = i;
                dr[1] = "【孟子E章】" + i.ToString() + " 前端传递的参数的值分别是:" + PA + ", " + PB;
                DT.Rows.Add(dr);
            }
            return DT;
        }


        private string DataTable2Json(System.Data.DataTable dt)
        {
            StringBuilder TB = new StringBuilder();
            TB.Append("{\"");
            TB.Append(dt.TableName.ToString());
            TB.Append("\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                TB.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    TB.Append("\"");
                    TB.Append(dt.Columns[j].ColumnName);
                    TB.Append("\":\"");
                    TB.Append(dt.Rows[i][j].ToString());
                    TB.Append("\",");
                }
                TB.Remove(TB.Length - 1, 1);
                TB.Append("},");
            }
            TB.Remove(TB.Length - 1, 1);
            TB.Append("]");
            TB.Append("}");
            return TB.ToString();
        }  


        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod()]
        public string GetUsers()
        {
            List<User> users = new List<User>()
            {
                new User { UId = 1, Name = "Brij", Address = "Noida"},
                new User { UId = 2, Name = "Rahul", Address = "New Delhi" },
                new User { UId = 3, Name = "John0", Address = "Chris"}
            };

            JavaScriptSerializer ser = new JavaScriptSerializer();
            return ser.Serialize(users);
        } 
    }

    public class User
    {
        public int UId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

}













相关文章推荐

Jquery 调用asp.net ajax (web service/static page method)的示例(二)---复杂参数

示例二(复杂参数的情况)     对于这种情况下的调用,客户端使用到一个小技巧,即:创建DTO 对象 (Data transfer object  ),个人常称之为 JSON包装对象 前台页面...

利用JQuery的$.ajax()可以很方便的调用asp.net的后台方法。

先来个简单的实例热热身吧。 1、无参数的方法调用 asp.net code: using System.Web.Script.Services;         [WebMethod]...

通过jQuery调用ASP.NET的AJAX

传统上,在ASP.NET页面中实现AJAX的方法是拖放一个ScriptManager控件,并进行一系列的设置和相关编程。但事实上,这并不是理想的解决方案。使用jQuery来调用ASP.NET后台的方法...
  • jyee721
  • jyee721
  • 2012年06月24日 01:41
  • 1862

jQuery通过ajax调用ASP.NET函数

PHP自然不在话下,如今要用ASP.NET,折腾了一大通,终于好了,记录一下。 首先,使用了AjaxPro,这玩意果然强大,直接调用了C#中的函数,正用着,发现jQuery不行了,网上搜了一...
  • ljhdlmu
  • ljhdlmu
  • 2015年03月19日 22:15
  • 240

jQuery Ajax 方法调用 Asp.Net WebService 的详细例子

这很常用,搜索了一下博客园的“找找看”和谷歌,看到大部分都是转载于一两篇文章(而且来源还不是博客园),有的是简单的说一点无法运行,给初学者的调试和学习带来不方便,我在这里将jQuery Ajax 调用...

Asp.net中JQuery、ajax调用后台方法总结

Asp.net中JQuery、ajax调用后台方法总结 2013-11-04 08:26:26     我来说两句       作者:李社河 收藏    我要投稿 通过上一篇文章...

Asp.net中JQuery、ajax调用后台方法总结

通过上一篇文章实例的实现,整个过程当中学习到很多知识点,了解了Jquery、Ajax在asp.net中的运用,加以总结,其实原理都是一样的,理解了一种,其他的注意很少的区别就可以了、灵活运用: 主要...
  • lishehe
  • lishehe
  • 2013年11月01日 08:57
  • 12949

JQuery的$.ajax()调用asp.net的后台方法样例代码

引入头文件:                                using System.Web.Script.Services;                           ...
  • amohan
  • amohan
  • 2012年07月27日 19:17
  • 865

jQuery Ajax 调用 ASP.NET WebServices + (POST)->JSON 数据传递,一种开发高效的模式

【jQuery Ajax 调用 ASP.NET WebServices + (POST)->JSON 数据传递,一种开发高效的模式】 jQuery是目前前端页面最好的Javascript"封装"模式...
  • kimiqiu
  • kimiqiu
  • 2011年03月28日 18:00
  • 2258

JQuery Ajax调用asp.net后台方法

利用JQuery的$.ajax()可以很方便的调用asp.net的后台方法。 先来个简单的实例热热身吧。 1、无参数的方法调用 asp.net code: [c...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:asp.net 调用jquery ajax
举报原因:
原因补充:

(最多只允许输入30个字)