ASP.NET在服务器端传递javascript值

时间:2010-09-06 06:17:45

标签: asp.net ajax

您如何在服务器端(C#)传递客户端(JS)值?

e.g。

我有一个生成的表(在上传图像之后)并且它包含图像,我想选择图像并将ID丢回服务器端。

我使用的上传是JQuery Uploadify,我有一个“onComplete”功能

(simple code)
'onComplete': function (event, queueID, fileObj, response, data) {
    $('#imgs').append('<img id="' + queueID + '" src="' + response + '" alt="' + response + '" />');

我该怎么做?

2 个答案:

答案 0 :(得分:0)

你使用的是Asp.net Forms吗?如果是这样,您是否了解页面生命周期的概念及其如何影响页面状态?

我建议在这一个中一直使用javascript,请参阅jQuery + AJAX。

答案 1 :(得分:0)

要从javascript向服务器发送值,您有几个选择:

  1. 如果您想留在当前页面,请使用AJAX
  2. 重定向到服务器端脚本并传递查询字符串中的值
  3. 让我们考虑第一种情况:

    假设您有一个能够在服务器上接收值的Web方法:

    <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" %>
    <script type="text/C#" runat="server">
        // Server side script in the code behind that will receive
        // the value: The method needs to be static
        // and decorated with the WebMethod attribute
        [System.Web.Services.WebMethod]
        public static string Foo(string id)
        {
            return "ok";
        }
    </script>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head id="Head1" runat="server">
        <title></title>
        <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(function () {
                // Send an AJAX request to the server
                $.ajax({
                    url: '/default.aspx/foo',
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    // Pass the value as JSON string
                    // You might need to include json2.js for the JSON.stringify
                    // method: http://www.json.org/json2.js
                    data: JSON.stringify({ id: 'someId123' }),
                    success: function (result) {
                        // The result is also JSON
                        alert(result.d);
                    }
                });
            });
        </script>
    </head>
    <body>
        <form id="Form1" runat="server">
    
        </form>
    </body>
    </html>