BUlle7
BUlle7

Reputation: 161

How to access session variable in asp.net mvc?

How to access session variable after post in ajax Asp.net Mvc. So far i have tried to store the session value in hidden field and declaring 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 });
    }

In my view

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

Upvotes: 0

Views: 4836

Answers (1)

Shyju
Shyju

Reputation: 218702

You can send that as part of the json response. Add a new property to the anonymous object you are passing to the Json method.

 [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 });
 }

And in your ajax method's done event you can read the shouldShowFlag property value of the response came back.

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

Upvotes: 1

Related Questions