2017-04-24 57 views
0

當我在下面的操作正在進行時開始不同的操作時,我無法獲取會話值;MVC並行事務和會話對象

$.ajax({ 
     type: 'GET', 
     cache: false, 
     url: '/Home/StartOperation', 
     dataType: 'json', 
     data: { customerId: $("#txtCustomerId").val() }, 
     error: function (xhr, status, error) { 
     $("#textlabel").text(error) 
     }, 
     success: function (result) { 
     $("#textlabel").text(result.Result) 
     } 
    }); 

控制器端;

public ActionResult StartOperation(string customerId) 
    { 
     Session["OperationId"] = "operationid"; 
     // Some web api transactions (This operations takes a few minutes.) 

     var data = new { Result = "Operation Completed." }; 
     return Json(data, JsonRequestBehavior.AllowGet); 
    } 

我可以肯定Session["OperationId"]不爲空,然後我打電話給我的行動取消了正在進行的Web API交易;

$(function() { 
     $('#btnCancelLogin').on('click', function() { 
      $.ajax({ 
       type: 'GET', 
       cache: false, 
       url: '/Home/CancelOperation' 
      }); 
     }); 
    }); 

控制器端;

public ActionResult CancelOperation() 
{ 
    String operationId = Session["OperationId"] as String // return null 
    //Cancel operations 
} 

爲什麼Session["OperationId"]總是空的CancelOperation()方法?感謝您的建議。

+0

嘗試:'(字符串)會議[「OperationId 「]' – Sajal

+0

@SajalS,沒有工作,除了我沒有投射,但會議[」OperationId「]爲空。 – oyenigun

+0

您可以打開瀏覽器控制檯並檢查Session [Key]是否在StartOperation方法期間實際創建? – Sajal

回答

0

如果您從ajax端獲取數據進行開始操作,您應該使用post。其實你的ajax類型是不正確的。

$.ajax({ 
     type: 'POST', 
     cache: false, 
     url: '/Home/StartOperation', 
     dataType: 'json', 
     data: { customerId: $("#txtCustomerId").val() }, 
     error: function (xhr, status, error) { 
     $("#textlabel").text(error) 
     }, 
     success: function (result) { 
     $("#textlabel").text(result.Result) 
     } 
    }); 

或者,如果你想採取從控制器的數據,你應該返回數據

public ActionResult StartOperation(string customerId) 
    { 
     Session["OperationId"] = "operationid"; 
     // Some web api transactions 
     return json(customerId); 
    } 

還你的Ajax應該是這樣的

$.ajax({ 
     type: 'GET', 
     cache: false, 
     url: '/Home/StartOperation', 
     dataType: 'json', 
     data: { customerId: $("#txtCustomerId").val() }, 
     error: function (xhr, status, error) { 
     $("#textlabel").text(error) 
     }, 
     success: function (result) { 
     $("#textlabel").text(result.Result) 
     } 
    }); 
+0

我已經在一些web api交易後返回json數據,我編輯我的帖子。 – oyenigun