X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Monday, February 16, 2015

Using local storage in jquery

Introduction for using local storage in jquery
Local storage is basically used to store the information at client side i.e, within user browser. Local storage can accommodate more data unlike cookies and the data is secure too.

How localstorage is better than Cookies ?
Below are the pros of localstorage -

  • localstorage is supported by modern browsers out now.
  • localstorage can store nearly 5 MB of data where as cookies can only store 4 KB
  • localstorage data has not been sent in HTTP header unlike cookies.

Above only few pros have been listed since this post is on using the localstorage in our project.

How to use localstorage in my project ?

So i will use the same list of files as i have created in my earlier post. You can find that post here.

And my javascript file has been modified to introduce localstorage. So here i am going to store the value of "Category Name" field (created in previous post) in localstorage as you see below -

$(document).ready(function () {
 $("#saveCategory").click(function () {
  
  var categoryName = $("#CategoryName").val();

  localStorage.setItem('name', categoryName);

  if($("#frmCategory").valid())
   $("#frmCategory").submit();
 }); 
});
In the above code "Category Name" field value is being stored in localstorage having key 'name'.

Now to display the value of localstorage (as alert box)  i will create a new action method as shown below and i change my post action method like this -

[HttpPost]
public ActionResult Index(Category catgr)
{
 return RedirectToAction("TestAction");
}

public ActionResult TestAction()
{
 ViewBag.Message = "Your test page.";
 return View("Test");
}
As you can see above new action method "Test Action" has been added and it is calling "Test.cshtml". So this page is just created to display the localstorage (in alert box).

So below is the code to display the value stored in localstorage -

<script type="text/javascript">

 var value = localStorage.getItem('name');

 alert(value);

 localStorage.removeItem('name');
</script>
So the above script is being added in "Test.cshtml". Make sure you remove the item added in the localstorage once its used because the value will be there till localstorage is being removed or cleared and it could cause some unexpected results.

Hope you enjoyed this article. Please put your comments below.





No comments:

Post a Comment

Comments Section