2017-03-07 74 views
-1

我有一個mvc項目。我想用javascript創建會話,並能夠在頁面的控制器中訪問它。 我已經嘗試了不同的選擇,但沒有爲我工作......我試過的東西 之一是:如何在javascript中創建會話並在控制器中訪問它mvc

查看:

<script> 
    @Session["TestingSession"]="Hello..."; 
</script> 

但價值並沒有經歷到控制器中的操作 - 值爲空。

控制器:

var a=Session["TestingSession"]; 

什麼想法?

+1

'Session'是服務器端。 Javascript是客戶端。您需要將值傳遞給服務器(例如使用ajax)並將其設置在控制器 –

+0

好。我真的不知道如何使用Ajax。你能給我更具體的方向嗎?謝謝 – Anonymous

+1

然後時間讓你做一些研究:) –

回答

0
$(function(){ 
    $.ajax({ 
    url  :'ajax page url', 
    method :'get/post', 
    data  : variable containing data, 
    success:function(html) 
    { 
     alert('success'); 
    } 
    }) 
}); 

,比屆AJAX頁面

0

上添加值JavaScript是服務器端,你將不得不通過AJAX的變量傳遞給服務器。

進行ajax請求的最簡單方法(個人意見)是使用jQuery庫。

這是如何的jQuery做一個Ajax請求:

$(function() { 

     $.ajax({ 
     method: "POST" 
     ,data: { 
      sessionVariable: variable 
     } 
     ,url: //enter the url of your controller/action which the session variable is being sent to, and handled by the server. 
     ,success: function(returnedData){ 
      alert("Session successfully sent to the server"); 
      // you could return something from the controller with more info and display this using the returnedData object. 
     } 
     ,error: function(){ 
      alert("something went wrong"); 
     } 
    }); 
}) 

更多信息ňjQuery的AJAX請點擊此鏈接>http://api.jquery.com/jquery.ajax/

相關問題