在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 ?
      });

关于javascript - 如何在ASP.NET MVC中访问 session 变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35123123/

10-12 03:25