如何在 asp.net mvc 中访问会话变量

本文关键字:访问 会话 变量 mvc net asp | 更新日期: 2023-09-27 18:32:38

如何在 ajax Asp.net Mvc 中发布后访问会话变量。 到目前为止,我已经尝试将会话值存储在隐藏字段中并声明会话值。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
});

如何在 asp.net mvc 中访问会话变量

您可以将其作为 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 ?
      });