jquery表单数据反序列化为字典

1.前台代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication10.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$.fn.GetPostData = function () {
var data = {};
var k = false;
$(this).find(".datacontrol").each(function (i, value) {

var field = $(value).attr("name");
if (field == null) {
field = $(value).attr("id");
}
if (value.tagName == "INPUT") {
if (value.type == "checkbox") {
if ($(value).prop("checked") == true) {
if (data[field]) {
var a = +$(value).val();
if (a == "") {
a = "1";
}
data[field] = data[field] + "," + a;
k = true;
} else {
var a = +$(value).val();
data[field] = "1"
k = true;
}
}
}
else if (value.type == "radio") {
if ($(value).attr("checked") == true) {
data[field] = $(value).val();
k = true;
}
}
else {
if ($(value).val() != "") {
data[field] = $(value).val();
k = true;
}
}
}

else if (value.tagName == "SELECT") {
if ($(value).val() != "") {
data[field] = $(value).val();
k = true;
}
}
else if (value.tagName == "DIV") {
data[field] = $(value).html();
k = true;
}
else if (value.tagName == "IMG") {
data[field] = $(value).attr("src");
k = true;
}
else if (value.tagName == "SPAN") {
data[field] = $(value).html();
k = true;
}
else if (value.tagName == "TEXTAREA") {
if ($(value).val() != "") {
data[field] = $(value).val();
k = true;
}
}

});
if (!k) {
return null;
}
return data;
}
$(function () {

$("#btn").on("click", function () {
//var postParam = new Object();
//alert($("#t1").val());
//postParam.t1 = $("#t1").val();
//postParam.t2 = $("#t2").val();
//postParam.t3 = $("#t3").val();
//postParam = JSON.stringify(postParam);
var postParam = $("#form1").GetPostData();
postParam = JSON.stringify(postParam);
$.post("webform1.aspx?_method=postParam&data="+postParam, function (data) { });
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" id="btn" name="btn" value="点击我" />
<input type="text" id="t1" name="t1" value="t11" class="datacontrol"/>
<input type="text" id="t2" name="t2" value="t22" class="datacontrol"/>
<input type="text" id="t3" name="t3" value="t33" class="datacontrol"/>
</form>
</body>
</html>

2.后台代码

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication10
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
switch (Request["_method"])
{
case "postParam":
var dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(Request["data"]);
break;

}
}
}
}
原文地址:https://www.cnblogs.com/kexb/p/5176437.html