2012-05-15 34 views
0

我有一個頁面,用戶在根據這些關鍵字找到資源之前提交了多個關鍵字。我有一個加載所有關鍵字的jQuery數組,我想將該jQuery數組傳遞到下一個結果頁面。我試圖找出最好的方法來做到這一點。我已經嘗試將數組放入字符串並通過URL傳遞,但無法正確URLEncode它。我也嘗試過使用window.location,但這一直效果不佳。這看起來很簡單,但我正在圈圈。這是一個我想保存在內存中的一維數組,然後將它傳遞給下一個aspx頁面。什麼是最好的方法?下面是我的代碼,因爲它現在是不正確的。將jQuery數組傳遞到C#頁面的最佳方法

//When get resources button clicked show current array values 
$("#nihSearch_btnResults").click(function() { 
    //get number of tabs in the holder 
    gettabs = $("div#keys > div.tab").size(); 
    output = ""; 
    //loop through the tabs   
    $("div.tab span").each(function() { 
     //get the text of the tab 
     var kw = $(this).text(); 
     //add it to the array 
     keywords.push(kw); 
    }); 

    var jsonstring = JSON.stringify(keywords); 
    alert(jsonstring); 
}); 
+0

有你不想使用cookie的一個原因? –

+0

這篇文章怎麼樣?它似乎回答你的問題。 http://stackoverflow.com/questions/320291/how-to-post-an-array-of-complex-objects-with-json-jquery-to-asp-net-mvc-control –

+0

Will,我想我可以使用cookie ......湯姆,這似乎比我想做的更深入。 – Jason

回答

0

我能夠通過URL做到這一點。我將數組轉換爲字符串,用下劃線替換所有空格,然後使用window.location移動到下一頁。在那裏,我使用C#頁面中的Page_Load將下劃線替換回空格,並使用「split」重新創建數組。

jQuery的

//convert array into a string 
    var keystring = keywords.join(","); 
    //make keystring all lower case and replace spaces with hyphens 
    keystring = keystring.toLowerCase().replace(/ /g, '_'); 
    //Send it to the next page. 
    window.location = "Results.aspx?kws=" + keystring; 

C#

protected void Page_Load(object sender, EventArgs e) 
    { 
     //get keywords from URL 
     string urlkeys = Request.QueryString["kws"]; 
     //replace dashes with spaces 
     urlkeys = urlkeys.Replace("_", " "); 
     //split back into an array 
     string[] arr = urlkeys.Split(',');    
    } 
0

可以使用$.ajax方法和asp.net服務器端web-method

這裏發佈客戶端數據到服務器,我已執行代碼
http://blog.nitinsawant.com/2011/09/draft-sending-client-side-variables-to.html

  //js code to post data to server 
     var jsonData = "{'jsonData':'" + JSON.stringify(keywords) + "'}";//create string representation of the js object 
     $.ajax({ 
      type: "POST", 
      url: 'Test.aspx/AcceptData', 
      data: jsonData, 
      contentType: "application/json; charset=utf-8", 
      dataType: ($.browser.msie) ? "text" : "json", 
      success: function(msg) { 
       //call successfull 
       var obj = msg.parseJSON(); 
       alert(obj.d); //d is data returned from web services 

       //The result is wrapped inside .d object as its prevents direct execution of string as a script 
      }, 
      error: function(xhr, status, error) { 
       //error occurred 
       alert(xhr.responseText); 
      } 
     }); 

Web方法:

//C# code 
[System.Web.Services.WebMethod] 
public static string AcceptData(object jsonData) 
{ 
    Customer newCust =(Customer)JsonConvert.DeserializeObject(jsonData.ToString(),typeof(YourCustomClass)); 
    return "Server response: Hello "+newCust.FirstName; 
} 

問候
尼廷

相關問題