asp.net中使用json前后台传值

晨曦之光 发布于 2012/05/16 17:15
阅读 1K+
收藏 0

使用input控件onclick传递json比较简单,
使用asp:Button 服务器控件onclick会回发刷新页面使json的值丢失。
在Handler1.ashx中使用静态变量存储当两个人同时操作的时候会出现问题,如果您有好的解决办法,希望能于大家分享。
以下代码大多来源于网上,在此感谢作者。
//前台
<script src="JS/json2.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
var xmlHttp;

function createXMLHttpRequest()
{
    if (window.ActiveXObject)
{
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
{
        xmlHttp = new XMLHttpRequest();
    }
}

function doJSON() {

    createXMLHttpRequest();

    var car = getCarObject();

    xmlHttp.onreadystatechange = handleStateChange;

    xmlHttp.open("get", "Handler1.ashx?ts=" + new Date().getTime() + "&jsonStr=" + JSON.stringify(car), true);

    xmlHttp.setRequestHeader("content-type", "application/x-www-form-urlencode");
    xmlHttp.send(null);
}

function getCarObject()
{
    return new Car("Dodge","Coronet R/T",1968,"yellow");   
}

function Car(make,model,year,color)
{
    this.Make=make;
    this.Model=model;
    this.Year=year;
    this.Color=color;
}
   
function handleStateChange()
{
    if(xmlHttp.readyState == 4)
{
        if(xmlHttp.status == 200)
        {
            parseResults();
        }
    }
}

function parseResults(){

    var responseDiv = document.getElementById("serverResponse");
    if(responseDiv.hasChildNodes())
    {
       responseDiv.removeChild(responseDiv.childNodes[0]);
    }
   
    var responseText = document.createTextNode(xmlHttp.responseText);
    responseDiv.appendChild(responseText);
}

    </script>


<body>
    <form id="form1" runat="server">
    <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </cc1:ToolkitScriptManager>
    <div>
       <input type="button" value="Click here to send JSON data to the server" onclick="doJSON();" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="doJSON();" />
            </ContentTemplate>
        </asp:UpdatePanel>
       
    </div>
    </form>
</body>


//Handler1.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;

namespace JSonDemo
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string carJson = context.Request.Params["jsonStr"];
            // 可以通过,但在客户端的JSON.parse()处报:语法错误
            //JSonDemo._Default.Car car = (JSonDemo._Default.Car)JavaScriptConvert.DeserializeObject(carJson, typeof(JSonDemo._Default.Car));
            //string responseStr = JavaScriptConvert.SerializeObject(car);

            // 不能通过,报错:该字符串未被识别为有效的 DateTime。
            //Serializer s = new Serializer(typeof(Car));
            //Car car = (Car)s.Deserialize(carJson);
            //string responseStr = s.Serialize(car);

            //context.Response.Write(responseStr);
            MyProperty = carJson;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public static string MyProperty { get; set; }
    }
}


//后台
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;

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

        }
        [DataContract]
        [Serializable]
        public class Car
        {
            public Car()
            { }
            private string make;

            [DataMember]
            public string Make
            {
                get { return make; }
                set { make = value; }
            }

            private string model;
            [DataMember]
            public string Model
            {
                get { return model; }
                set { model = value; }
            }

            private int year;
            [DataMember]
            public int Year
            {
                get { return year; }
                set { year = value; }
            }

            private string color;
            [DataMember]
            public string Color
            {
                get { return color; }
                set { color = value; }
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
           
            string adfadfas = Handler1.MyProperty;
            //string sJson = "{/"Make/":/"Dodge/",/"Model/":/"Coronet R/T/",/"Year/":1968,/"Color/":/"yellow/"}";
            Car car = new Car();
            Type type = car.GetType();
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(car.GetType());
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(adfadfas));
            car = serializer.ReadObject(ms) as Car;
            string Makes = car.Make;


        }
       
    }
}

 


原文链接:http://blog.csdn.net/maji9370/article/details/5479514
加载中
返回顶部
顶部