簡體   English   中英

如何在ASP.NET MVC中訪問會話變量?

[英]How to access session variable in asp.net mvc?

在ajax Asp.net Mvc中發布后如何訪問會話變量。 到目前為止,我已經嘗試將會話值存儲在隱藏字段中並聲明sessionvalue。 var sesVal ='@Session [“ show_flag”]';

 public ActionResult EditCustomer(int id = 0)
    {
      InfoModel infoObj= new InfoModel();
      if (Session["show_flag"] != null){
      ViewBag.show_flag= Convert.ToBoolean(Session["show_flag"]);
      Session["show_flag"] = null;
       return View(infoObj);
      }
    }

    [HttpPost]
    public ActionResult EditCustomer(InfoModel infoObj, int id)
    {
     string url = "";
     Session["show_flag"] = infoObj.Show_flag(infoObj);//returns true or false
     infoObj.EditCustomer(infoObj,id);
     url = Url.Action("ViewCustomer");
     return Json(new { newurl = url });
    }

在我看來

 function EditCustomer() {
    var $form = $('#EditCustomerForm');
    $.ajax({
    type: "POST",
    url: '@Url.Action("EditCustomer", "Customer", new { id = ViewContext.RouteData.Values["id"] })',
    json: true,
    data: $form.serialize()
    }).done(function (data) {
    RedirectUrl = data.newurl;
    //Session["show_flag"] how can i get session value to check the condition here
});

您可以將其作為json響應的一部分發送。 將新屬性添加到要傳遞給Json方法的匿名對象。

 [HttpPost]
 public ActionResult EditCustomer(InfoModel infoObj, int id)
 {
     var showFlag = infoObj.Show_flag(infoObj);
     Session["show_flag"] = showFlag;
     infoObj.EditCustomer(infoObj,id);
     var url = Url.Action("ViewCustomer");
     return Json(new { newurl = url, shouldShowFlag = showFlag });
 }

在ajax方法的done事件中,您可以讀取返回的響應的shouldShowFlag屬性值。

var $form = $('#EditCustomerForm');
$.ajax({
        type: "POST",
        url: '@Url.Action("EditCustomer", "Customer", 
                                      new { id = ViewContext.RouteData.Values["id"] })',
        json: true,
        data: $form.serialize()
      }).done(function (data) {

          var newUrl = data.newurl;
          var shouldShow = data.shouldShowFlag;
          alert(shouldShow);
          // window.location.href=newUrl; reload to the new url ?
      });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM