前台:[切记:每个表单元素, 都应该带有name, 否则是取不到的。]
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
- <!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 src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
- <script type="text/javascript">
- function test() {
- $("#Action").val(1);
- var vals = $("#tableForm :input").serialize(); //var vals = $("#form1").serialize();//两种都可以,但后一种会多取__ViewState这个系统hidden
- $.post("Default3.aspx", vals, function (data) {
- alert("前台取得值:\n" + vals+"\n后台取得值:\n"+data);
- });
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <table id="tableForm" style="border-collapse:collapse;" cellpadding="5" cellspacing="2" border="1">
- <tr><td>姓名:</td><td><input id="Name" name="Name" type="text" value="刘 军" /><input id="Action" name="Action" type="hidden" value="0" /></td></tr>
- <tr><td>密码:</td><td><input id="Pwd" name="Pwd" type="password" value="123456" /></td></tr>
- <tr><td>性别:</td><td>
- <input name="Gender" type="radio" checked="checked" value="Male" />男
- <input name="Gender" type="radio" value="Female" />女</td>
- </tr>
- <tr><td>爱好:</td><td>
- <input id="Checkbox1" type="checkbox" checked="checked" name="Hobby" value="1" />足球
- <input id="Checkbox2" type="checkbox" checked="checked" name="Hobby" value="2" />象棋</td>
- </tr>
- <tr><td>留言:</td><td><textarea id="Note" name="Note" cols="20" rows="2">+ |</textarea></td></tr>
- <tr><td>籍贯:</td><td>
- <select id="Select1" name="Home" >
- <option value="">---请选择---</option>
- <option value="湖南" selected="selected">湖南</option>
- <option value="湖北">湖北</option>
- </select></td>
- </tr>
- <tr><td colspan="2"><input id="Button1" type="button" value="测试" onclick="test()" /></td></tr>
- </table>
- </form>
- </body>
- </html>
后台:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Text;
- public partial class Default3 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (Request.Form["Action"] == "1") {
- Ajax();
- }
- }
- private void Ajax()
- {
- StringBuilder sb = new StringBuilder();
- foreach (string s in Request.Form.AllKeys) {
- sb.AppendFormat("{0}: {1}\n",s,Request.Form[s] );
- }
- Response.Write(sb.ToString());
- Response.End();
- }
- }
—————————————— 结果 —————————————
前台取得值:
Name=%E5%88%98+%E5%86%9B&Action=1&Pwd=123456&Gender=Male&Hobby=1&Hobby=2&Note=%2B++%7C&Home=%E6%B9%96%E5%8D%97
后台取得值:
Name: 刘 军
Action: 1
Pwd: 123456
Gender: Male
Hobby:
1,2
Note: + |
Home: 湖南