c# web页面向后台传递数据的几种方法

        C#web页面向后台传递数据有很多方法,可以使用服务器控件,也可以使用ajax,本文介绍几种常用的方法:

方法
(1)使用服务器控件;
(2)使用ajax+aspx;
(3)使用ajax+ashx;
(4)使用ajax+aspx静态方法。

       下面,我们写个例子,详细介绍一下这几种方法的使用:

第一步:创建ajax_01.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ajax_01.aspx.cs" Inherits="web_ajax_01" %>

<!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/javascript" src="../jquery/jquery-1.8.0.min.js"></script>
	<script type="text/javascript">

	    function method1() {

	        $.ajax({
	            type: "Post",
	            url: location.href,
	            data: $("#form1").serialize(),	           
	            success: function(data) {
	                if (data="success")
	                    alert("信息确认成功!");
	            },
	            error: function(err) {
	               alert("错误");
	            }
	        });

	    }

	    function method2() {

	        $.ajax({
	            type: "Post",
	            url: "ajax_01.ashx",
	            data: $("#form1").serialize(),
	            success: function(data) {
	                if (data = "success")
	                    alert("信息确认成功!");
	            },
	            error: function(err) {
	                alert("错误");
	            }
	        });

	    }

	    function method3() {

	        var name = $("#name").val();
	        var age = $('input[name=age]:checked').val()
	        var code = $("#code").val();

	        var language = [];
	        $("input[name='language']:checked").each(function() {
	           language.push($(this).val());
	        });  
	        
	        var comment = $("#comment").val();
	        
	        $.ajax({
	            type: "Post",
	            url: "ajax_01.aspx/read3",
	            data: "{'name':'" + name + "','age':'" + age + "','code':'" + code + "','language':'" + language + "','comment':'" + comment + "'}",
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function(data) {
	                alert(data.d);
	            },
	            error: function(err) {
	                alert("错误");
	            }
	        });

	    }

	    function method4() {

	        var json = $('#form1').serialize();

	        $.post(location.href, json, function(data) {
	            if (data ="success")
	            { 
	                alert("成功!");    
	            }
	            
	        });

	    }

	    function method5() {

	        var json = $('#form1').serialize();

	        $.post("ajax_01.ashx", json, function(data) {
	            if (data = "success") {
	                alert("成功!");
	            }

	        });

	    }    
	    
	
	</script>
    
</head>
<body>
    <form id="form1">
    <input id="action"  name="action" value="read" type="hidden"  />
    <div>
        <table border="0">
            <tr>
                <td>姓名:</td>
                <td>
                    <input id="name" name="name" type="text" />
                </td>
            </tr>         
            <tr>
                <td>年龄段:</td>
                <td>
                    <input type="radio" name="age" value="18" />小于18岁
                    <input type="radio" name="age" value="18-40" checked="checked" />18-40岁
                    <input type="radio" name="age" value="40" />40以上
                </td>
            </tr>           
            <tr>
                <td>编程时间:</td>
                <td>
                    <select name="code" id="code">
                        <option value="never">不编程</option>
                        <option value="6" selected="selected">不到六个月</option>
                        <option value="6-12">六到十二个月</option>
                        <option value="12-24">十二到二十四</option>
                        <option value="24">大于二十四</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>编程语言:</td>
                <td>
                    <input name="language" type="checkbox"  value="java" />java
                    <input name="language" type="checkbox"  value="c" />c
                    <input name="language" type="checkbox"  value="c++" />c++
                    <input name="language" type="checkbox"  value="c#" />c#
                    <input name="language" type="checkbox"  value="vb" />vb
                </td>
            </tr>
            <tr>
                <td>建议:</td>
                <td>
                    <textarea name="comment" cols="40" rows="5" id="comment"></textarea>
                </td>
            </tr>
        </table>
    
    </div>
    </form>    
    
    <div>
        <BUTTON  οnclick="method1();return false;" type="button">方法一</BUTTON>
        <BUTTON  οnclick="method2();return false;" type="button">方法二</BUTTON>
        <BUTTON  οnclick="method3();return false;" type="button">方法三</BUTTON>
        <BUTTON  οnclick="method4();return false;" type="button">方法四</BUTTON>
        <BUTTON  οnclick="method5();return false;" type="button">方法五</BUTTON>
        
    </div>
    
</body>
</html>
第二步:编写ajax_01.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class web_ajax_01 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string action = "";
        if (Request.Form["action"] != "")
        action = Request.Form["action"];

        switch (action)
        {
            case "read"://查询数据
                read();
                break;
          
            default:
                break;

        }
    }
    
    private void read()
    {
        string name = Request.Form["name"];
        string age = Request.Form["age"];
        string code = Request.Form["code"];
        string language = Request.Form["language"];
        string comment = Request.Form["comment"];
        
        Response.Clear();
        Response.Write("success");
        Response.End();

    }

    [WebMethod]
    public static string read3(string name, string age, string code, string language, string comment)
    {
        return name + age + code + language + comment;

    }

}
第三步:编写ajax_01.ashx
<%@ WebHandler Language="C#" Class="ajax_01" %>

using System;
using System.Web;

public class ajax_01 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

        string action = context.Request["action"];
        if (action == "read")
        {
            read(context);                
        }        
        
        context.Response.Write("Hello World");
        
    }

    private void read(HttpContext context)
    {
        string name = context.Request.Form["name"];
        string age = context.Request.Form["age"];
        string code = context.Request.Form["code"];
        string language = context.Request.Form["language"];
        string comment = context.Request.Form["comment"];

        context.Response.Clear();
        context.Response.Write("success");
        context.Response.End();
        
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}
说明:
(1)方法1和4都是向aspx传递数据;
(2)方法2和5都是向ashx传递数据;
(3)方法3是向aspx的静态方法传递数据;

ashx注意事项:
(1)ajax方法中的contentType如果指定必须指定为“application/x-www-form-urlencoded”,否则在ashx中request.form获取不到数据;
(2)如果dataType为json,想要jQuery自动解析json数据,ashx必须返回严格的json数据,而且必须是双引号(用反义字符去反义)的格式,如: context.Response.Write("{\"d\":\"Hello World\"}"),否则jquery会解析json失败;
(3)如果因为contentType未设置或者不是“application/x-www-urlencoded”类型,reque.form获取不到数据,可以通过context.Request.InputStream来获取请求内容;
(4)在请求ashx中data参数有这几种形式: data:{'a':'aa','b':'bb'}, data:"a=aa&b=bb",data:{a:'aa',b:'bb'},这三种数据都可以通过request.form[""]来获取到。

aspx的静态方法注意事项:
  (1)aspx的后台方法必须静态,而且添加webmethod特性;
  (2)在ajax方法中contentType必须是“application/json”;
  (3)data传递的数据必须是严格的json数据,如"{'a':'aa','b':'bb'}",而且参数必须和静态方法的参数一 一对应;
  (4)aspx的后台方法返回的数据默认形式是“{'d':'返回的内容'}”,所以如果dataType指定为"json"必须通过data.d来获取返回数据。

个人看法:
静态方法非常不灵活,写起来还比较复杂;
具体的写法不只文中的几种方法,还有其它的写法,只要能工作就可以;
服务器控件的方法没有介绍,直接调用就好了,个人非常喜欢,就喜欢简单的,效率没得说。

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值