sanjivani
sanjivani

Reputation: 63

How to clear session using jquery?

I am developing mvc application. I used session in view and controller. First when i select value from dropdown list. selected value is managed in view and controller. but when I again select value from dropdown list , that time on change event I want to clear session.

below is my code for view

@model IEnumerable<StockWatch.DTO.ProductDTO>

@using GridMvc.Html
@using System.Web.UI.WebControls;

@{
    ViewBag.Title = "Index";
    int VendorId = Convert.ToInt32(Session["vendorId"]);
}

<!DOCTYPE html>

<html>
    <head>
         <link href="@Url.Content("~/Content/Custom1.css")" rel="stylesheet" type="text/css" />    
   </head>
<body> 

     @if (Model == null)
     {

    <div id="vendorDropdownDiv" class =" row-fluid Span9" style ="margin-bottom :15px">

                   <div class="span6"  >
                           <div class="span4" style="margin-left:35px;" >
                         <label >Vendor</label>
                    </div>
                    <div class="span6" >
                      @Html.DropDownList("VendorId", ViewData["list"] as SelectList, "-- Select vendor --", new { @id = "vendorDropdown", @name = "VendorId" })

                  </div>
                 </div>                              

                 <div class="span11" style="text-align:right">           
                <input class="btn btn-primary" type="submit" value="Create" id="create"/>
                 <input class="btn btn-default" value="Cancel" style="width:45px;" onclick="window.location.href='@Url.Action("index")    '"/>
           </div>
              </div> 
     }    

  <div id="indexview"></div>

     @if (Model != null)
     {
    <div id="modeldiv" class="span12" style="margin-left:0px;margin-right:0px;">
       <div class="row-fluid" style="margin-top:30px;margin-bottom:10px;">
       <div class="listheading span9" style="font-size:22px;">Products</div>

      <div class="createlink span3" style="text-align:right;margin-left:10px;">
       @Html.ActionLink("+ Add Product", "Create")
    </div>
  }     
</body>
</html>

<script>
    $(document).ready(function () {      
        $('#vendorDropdown').change(function () {                  
        }); 
    });
</script>

and controller code as below

       public ActionResult Index(int VendorId=0)
    {
        if (VendorId == 0)
        {
            VendorId = Convert.ToInt32(Session["vendorId"]);
        }

        VendorService vendorService = new VendorService();
        SelectList SelectList = new SelectList(vendorService.GetAll().OrderBy(t => t.Name), "Id", "Name", VendorId);
        ViewData["list"] = SelectList;

        var Categorylist = new SelectList(new[] { "Dull", "Anodised", "All" });

        ViewData["Categorylist"] = Categorylist;

        if (VendorId != 0 )
        {
            Session["vendorId"] = VendorId;
            ProductService productService = new ProductService();
            var productlist = new List<ProductDTO>();             
            productlist = productService.GetAll().Where(x => x.VendorId == VendorId).ToList();

            return View(productlist );
        }
        else
        {
            return View();
        }
    }

here how to clear Convert.ToInt32(Session["vendorId"]); this session using jquery. thank u in advance

Upvotes: 1

Views: 19823

Answers (7)

Unexpected_error
Unexpected_error

Reputation: 48

Hi you can simply use sessionStorage.clear(); and localStorage.removeItem(keyname) or sessionStorage.removeItem(keyname).

Upvotes: 0

saeed rostami
saeed rostami

Reputation: 1

You can use JQUERY with ajax as below:

1 - in HTML file use a id tag, for example id="clear_session" .

2 - use "clear_session" click event for start ajax in your js file :

var clear_session    = $("#clear_session"); 
clear_session.click(function(){
        $.ajax({
                type: "POST",
                url: "index.php",
                data: "do=clear_session",
                complete: function(data){ 

                        // your desired finishing function

                }           
        });     
});

3 - use this code in index.php file :

if ($_POST['do'] == 'clear_session')
{
    // your desired function
}

please reply for more guide. Saeed Rostami. IT Engineer in I.R.I +98 935 516 90 58

Upvotes: -1

David McEleney
David McEleney

Reputation: 3813

As the session is stored server side - not client side, you'll need to instruct the server to destroy it. maing a request to an action method could do this -

Create an action method in your mvc site -

public class ControllerName
{
 public ActionResult DestroySession()
 {
     Session = null;
 }
}

then from the page, call the following javascript code:

<script>

$('#clearSessionButton').click(
function() {
    $.ajax('/ControllerName/DestroySession');
});

</script>

Upvotes: 3

Baximilian
Baximilian

Reputation: 885

I know it's maybe late but, I hope this will help you First of all, you need to be carefully when working with session. Better way it's to create some class that will be do all work with your session After what you will need to create controller which will help you to do all u want from js. You will have something like this:

public class SessionManager
{
    public static int VendorId
    {
        get { return Convert.ToInt32(HttpContext.Current.Session["vendorId"]); }
    }

    public static void SetVendorId(int id)
    {
        HttpContext.Current.Session["vendorId"] = id; 
    }

    public static void ClearVendorId()
    {
        HttpContext.Current.Session["vendorId"] = null;
    }
}

public class SessionManagerController : Controller
{
    [HttpPost]
    public ActionResult GetVendorId()
    {
        return Json(SessionManager.VendorId);
    }

    [HttpPost]
    public ActionResult SetVendorId(int id)
    {
        try
        {
            SessionManager.SetVendorId(id);
        }
        catch (Exception)
        {
            return Json("false");
        }
        return Json("true");
    }

    [HttpPost]
    public void ClearVendorId()
    {
        SessionManager.ClearVendorId();
    }
}

the way to call this methods from client you can choose by yourself.

and by the way, in your view:

 int VendorId = Convert.ToInt32(Session["vendorId"]);

you will use:

int VendorId = SessionManager.VendorId

Upvotes: 0

Shanker Paudel
Shanker Paudel

Reputation: 740

Sessions are maintained on server and could not removed on client without sending request to server.

As suggested by Patrick Hofman you can Create an action ClearSession and call it using $.ajax or $.get.

Upvotes: 3

Ankush Jain
Ankush Jain

Reputation: 6974

Create an action in your controller that will clear and abandon the session. You can call that action using jQuery ajax and your session will get cleared.

Upvotes: 0

hari
hari

Reputation: 1963

call $ajax or $post method to clear a session

     $.post("clearsessionAction",function(data){
        //clear your session 
     });

Upvotes: 0

Related Questions