2010-09-06 65 views
0

嗨如何在服務器端(C#)傳遞客戶端(JS)值?ASP.NET在服務器端傳遞一個javascript值

例如

我有一個生成的表格(上傳圖片後),它包含圖像,我想選擇圖像並將ID返回到服務器端。

我所用的JQuery Uploadify,我有 「的onComplete」 功能

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

我怎樣才能做到這一點的uploade?

+0

你的問題不是很清楚。 「扔」是什麼意思?你想要傳遞一個JavaScript值到服務器,以便做些什麼,或者你需要註冊一個值從服務器到JavaScript? – RPM1984 2010-09-06 06:31:10

+0

是的,這就是我的意思。傳遞一個值 – jaysonragasa 2010-09-06 06:36:39

回答

0

從JavaScript發送一個值,你有兩個選擇服務器:

  1. 使用AJAX,如果你想留在當前頁面
  2. 重定向到一個服務器端腳本,並傳遞值在查詢字符串

讓我們考慮第一種情況:

假設你已經能夠接收服務器上的值的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> 
+0

感謝達林。你有這樣的工作樣本嗎? – jaysonragasa 2010-09-06 07:06:32

+0

好吧,我得到它的工作。快速的問題。在「成功:功能(結果)」這是怎麼回事?如果我在服務器端方法中有2個參數,該怎麼辦?我怎麼能通過客戶端的價值? – jaysonragasa 2010-09-06 07:15:43

0

你使用Asp.net Forms嗎?如果是這樣,你確實理解頁面生命週期的概念以及它如何影響頁面的狀態?

我建議在這個版本中一直使用javascript,請參閱jQuery + AJAX。

相關問題