javascript - 如何在asp.net mvc中访问 session 变量?

标签 javascript c# jquery ajax asp.net-mvc-4

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

相关文章:

javascript - jQuery 单击将我带到页面顶部。但我想留在原地

c# - 在 .NET 3.5 中使用反射生成子类列表

javascript - 是否可以扩展私有(private)功能?

javascript - 在表格标题中绘制日历

javascript - 来自 URL 的 C3.js 线图颜色

javascript - Google recaptcha 无法与 AngularJS 一起使用

c# - 将 func<type, bool> 作为参数传递给异步方法时出错

c# - 如何使用 WeifenLuo DockPanel Suite 拒绝面板被拖动

php - 在 while 循环中处理一个 div

javascript - 如何防止停止滚动悬停 iFrame(完美滚动条)?