前台和后台数据传递综合总结

1.前台将Json字符串数据传递到后台进行处理

//var Json = '{"User":[{"UserName":"a","PassWord":"a"},{"UserName":"b","PassWord":"b"}]}';这是前台
            string json = Request.Form["Json"];
            JObject o = (JObject)JsonConvert.DeserializeObject(json);
            JToken arr = (JToken)o["User"];//此地返回的是多条记录,所以要遍历
            foreach (var token in arr)
            {
                Person p = JsonConvert.DeserializeObject<Person>(token.ToString());
                //在此对p进行增删改操作,p已经是一个实体类的实例
            }
            Response.End();

对Json字符串进行后台处理,需要应用到程序集Newtonsoft.Json.dll

另外:如果是一条记录的Json,处理方式是:

//var Json = '{"UserName":"c","PassWord":"c"}';这是前台
            string json = Request.Form["Json"];
            JObject o = (JObject)JsonConvert.DeserializeObject(json);
            JToken arr = (JToken)o;//此地返回的是一条记录,不进行选项选择都是一条,不用遍历
            Person p = JsonConvert.DeserializeObject<Person>(arr.ToString());
            //在此对p进行增删改操作,p已经是一个实体类的实例
            Response.End();

 2.组织对象,然后转换为Json字符串

var opts = {
                    UserName: "d",
                    PassWord:"d"
                };
                var json = jsonParseString(opts);

 方法jsonParseString 代码如下

//JSON对象转字符串
function jsonParseString(o) {
    try {
        if (o == undefined) { return ""; }
        var r = [];
        if (typeof o == "string") return "\"" + o.replace(/([\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
        if (typeof o == "object") {
            if (!o.sort) {
                for (var i in o)
                    r.push("\"" + i + "\":" + jsonParseString(o[i]));
                if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
                    r.push("toString:" + o.toString.toString());
                }
                r = "{" + r.join() + "}"
            } else {
                for (var l = 0; l < o.length; l++)
                    r.push(jsonParseString(o[l]))
                r = "[" + r.join() + "]";
            }
            return r;
        }
        return o.toString().replace(/\"\:/g, '":""');
    } catch (e) { return e.Message; }
}

 最终生成的json字符串为:var Json = '{"UserName":"d","PassWord":"d"}',满足传递到后台的需求

3.前台直接传递到自己的后台,添加Response.End();可以防止传递HTML到前台

4.后台将数据转换为Json传递到前台

这是后台代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Form["Type"] == "GetJson")
        {
            Person p = new Person();
            p.UserName = "e";
            p.PassWord = "e";
            string json = JsonConvert.SerializeObject(p);//此处将对象转换为Json了
            Response.Write(json);
            Response.End();
        }
    }

注意还可以将对象集合转换为Json,实例代码:

            List<Person> persons = new List<Person>();
            Person p = new Person();
            p.UserName = "f";
            p.PassWord = "f";
            persons.Add(p);
            persons.Add(p);
            string json = JsonConvert.SerializeObject(persons);//此处将对象转换为Json了 内容为 "[{\"UserName\":\"f\",\"PassWord\":\"f\"},{\"UserName\":\"f\",\"PassWord\":\"f\"}]"
            Response.Write(json);
            Response.End();

同时他还可以将DataTable转换为Json字符串,实例代码如下:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Form["Type"] == "GetJson")
        {
            DataTable dt = ZXGA.Utility.DbHelperOleDb.Query(App_Init.ConnStr(),"select * from jjdwb").Tables[0];
            string json = JsonConvert.SerializeObject(dt);
            Response.Write(json);
            Response.End();
        }
    }

 

下面是前台代码:

                $.post("test2.aspx", { Type: "GetJson" }, function (data) {
                    //var obj = $.parseJSON(data);//方法一
                    var obj = eval('(' + data + ')'); //方法二
                    alert(obj.UserName);
                });

 

posted on 2013-11-16 14:42  kingtiger  阅读(5983)  评论(1编辑  收藏  举报

导航