Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

ASP.NET (AJAX-JSON) implements object calls


May 08, 2021 JSON


Table of contents


Client

The code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ASP.NETA_JAX.aspx.cs" Inherits="_Default" %> 
<!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 runat="server"> 
<title></title> 
<script type="text/jscript"> 
function CallServer() { 
//JSON发送对象 
ServerSum("{name:'linyijia',age:'21'}"); 
} 
function GetRegister(rg, contex) { 
document.getElementById("TxtRegister").value=rg; 
} 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<br /> 
用户名:<input id="TxtNum1" type="text" /> 
<br /> 
服务器:<input id="TxtRegister" type="text" /><br /> 
<button id="SumBtn" type="button" onclick="CallServer()">登录</button> 
</div> 
</form> 
</body> 
</html> 

Server

The code is as follows:
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.Script.Serialization; 
public partial class _Default : System.Web.UI.Page ,ICallbackEventHandler 
{ 
Users u = null; 
protected void Page_Load(object sender, EventArgs e) 
{ 
//回调GetRegister方法 
string CallBackFun = Page.ClientScript.GetCallbackEventReference(this,"arg","GetRegister","context"); 
//创建ServerSum方法,在客户端调用的时候就,会回调GetRegister方法,把参数传给RaiseCallbackEvent(string eventArgument ),最后通过 
//GetCallbackResult()方法把返回值传给客户端 
string RegisterFun = string.Format("function ServerSum(arg,context){{{0};}}",CallBackFun); 
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"ServerSum",RegisterFun,true); 
} 
string mssage = string.Empty; 
#region ICallbackEventHandler 成员 
public string GetCallbackResult() 
{ 
return "服务器:你好,你的用户名为:" + u.Name + "你的年龄为" + u.Age; 
} 
public void RaiseCallbackEvent(string eventArgument) 
{ 
JavaScriptSerializer js = new JavaScriptSerializer(); 
u =js.Deserialize<Users>(eventArgument); 
} 
#endregion 
} 

Users class

The code is as follows:
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
/// <summary> 
///User 的摘要说明 
/// </summary> 
public class Users 
{ 
string name; 
public string Name 
{ 
get { return name; } 
set { name = value; } 
} 
string age; 
public string Age 
{ 
get { return age; } 
set { age = value; } 
} 
} 
Principle:

Using JSON to send an object to the server, the server overrides the GetCallbackResult and RaiseCallbackEvent methods by implementing the ICallbackEventHandler interface, deserated JSON in the RaiseCallbackEvent method, and returned the results to the client at the time of the callback

asp.net use jquery and ashx as ajax and json as data transfer

First, preparation

1. Build web application aspnetAjax

2. Build index .htm

3. Build a js folder and put .js jquery,

4. Build an ajax folder with aashx in it

5. In the js folder to build .js, generally we are a page corresponding to a js

6. In the ajax folder, build IndexHandler.ashx, generally a js page corresponds to a general user control, such a strong sense of hierarchy, but also very good maintenance.

Second, html page

Html page is simple, we want to use ajax to read the background to make a drop-down list, so the page will put a DIV on the line. The others are given to js.

Code:

<!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>
    <title>测试</title>
    <script src="js/jquery-1.2.3-intellisense.js" type="text/javascript"></script>
    <script src="js/index.js" type="text/javascript"></script>
</head>
<body>
    企业性质<div id="vocaspec"> </div>
    行业类型<div id="industr"> </div>      
</body>
</html>


Write IndexHandler.ashx code

Code:

namespace aspnetAjax.ajax
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>

    public class IndexHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
           context.Response.ContentType = "application/json";
           //接收提交过来的meth参数
            string meth = context.Request.Params["meth"].ToString(); 
            //根据参数调用不同的方法
            switch (meth) 
            {
                case "load":
                    loadjson(context);
                    break;
                case "add":
                    add(context);
                    break;
            }        
       }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
       //页面加载方法,调用BLL,获得数据
         private void loadjson(HttpContext context) 
        {
            //实例BLL
            VocaSpecSortBLL vocaSpec = new VocaSpecSortBLL();
            BLL.Owner ownerbll = new GYXMGL.BLL.Owner();
             
             DataSet ds = vocaSpec.GetList("");
             DataSet dsindustr = ownerbll.Getcharcte();
             //实例一个StringBuilder 用来拼接一个json数据
             StringBuilder sbvoca = new StringBuilder();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                sbvoca.Append("{\"voce\":[");
                int i = 1;
                int count = ds.Tables[0].Rows.Count;
                foreach (DataRow dr in ds.Tables[0].Rows) 
                {
                    if (i == count)
                    {
                        sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"}");
                    }
                    else
                    {
                        sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"},");
                    }
                    i++;
                }
                sbvoca.Append("]");
            }
            if (dsindustr != null && dsindustr.Tables[0].Rows.Count > 0) 
            {
                sbvoca.Append(",\"industr\":[");
                int i = 1;
                int count = dsindustr.Tables[0].Rows.Count;
                foreach (DataRow dr in dsindustr.Tables[0].Rows)
                {
                    if (i == count)
                    {
                        sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"}");
                    }
                    else 
                    {
                        sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"},");
                    }
                    i++;
                }
                sbvoca.Append("]");
            }
            sbvoca.Append("}");
            context.Response.Write(sbvoca.ToString());
            
            context.Response.End();
        }
    }
}

Let's change .js index

Code

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "../ajax/NewOwnerHandler.ashx",
        //我们用text格式接收
        dataType: "text",
        data: "meth=load",
        success: function(msg) {
            alert(msg);
            //显示后台数据
            $("#vocaspec").html(msg);
            // $("#industr").html(industr);
        }
    });
});

See the data below, which is the jason format data given to us by response in the ashx, and now we're going to take the data

Appears in the drop-down list. to traverse the array in johnson.

Code:

{
"voce":[{"code":"1","name":"农林水利"},{"code":"10","name":"军工"},{"code":"11","name":"农林"},{"code":"12","name":"水利(电)"},{"code":"13","name":"水电站"},{"code":"14","name":"输变线"},{"code":"15","name":"煤矿"},{"code":"16","name":"气田"},{"code":"17","name":"公路"},{"code":"18","name":"铁路"},{"code":"19","name":"民航"},{"code":"2","name":"能源"},{"code":"20","name":"信息产业"},{"code":"21","name":"化工"},{"code":"22","name":"机械"},{"code":"23","name":"冶金"},{"code":"24","name":"有色金属"},{"code":"25","name":"建材"},{"code":"26","name":"医药"},{"code":"27","name":"轻工"},{"code":"28","name":"农牧产品深加工"},{"code":"3","name":"交通"},{"code":"4","name":"通讯"},{"code":"5","name":"特色产业"},{"code":"6","name":"城市基础设施"},{"code":"7","name":"商贸流通"},{"code":"8","name":"旅游"},{"code":"9","name":"文体卫"}],
"industr":[{"code":"1","name":"国有"},{"code":"2","name":"私人"}]
}

Modify the index .js, traversing the json data to make the data a down-and-down list

Code:

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "../ajax/NewOwnerHandler.ashx",
        //json格式接收数据
        dataType: "json",
        //指点后台调用什么方法
        data: "meth=load",
        success: function(msg) {
             //实例2个字符串变量来拼接下拉列表
               var industr = "<select name=\"industr\"><option label=\"---请选择---\"></option>";
               var vocaspec = "<select name=\"vocaspec\"><option label=\"---请选择---\"></option>";
              //使用jquery解析json中的数据
               $.each(msg.voce, function(n, value) {
                     vocaspec += ("<option value=\"" + value.code + "\" label=\"" + value.name + "\">");
                     vocaspec += ("</option>");
                    });
                $.each(msg.industr, function(n, value) {
                     industr += ("<option value=\"" + value.code + "\" label=\"" + value.name + "\">");
                      industr += ("</option>");
                   });
             industr += ("</select>");
             $("#vocaspec").html(vocaspec);
            $("#industr").html(industr);
        }
    });
});

This example relates to knowledge points

1, the use of general handlers, receive request. And you can use the response data

string meth = context. R equest.Params["meth"]. ToString();

Because of the general handler

public class IndexHandler : IHttpHandler

He implements the IHttpHandler interface

2, json data format

3, use jquery ajax, and use jquery to parse the json data.