How ViewState Works---(Maintaning State with ViewState During PostBack to Server)

What exactly is a server PostBack? This actually occur when a page is not load directly through its link. Simply put, PostBack occur when a Button is click.How does ViewState relate with PostBack? ViewState is a dictionary that gets store our value before post back. i.e when a page is  loaded  from it's link. Illustration:Let us Examine, what happens if we try to access  a value through a default key which is stored in a ViewState Dictionary.The Question is :


Example 1.  Get a certain value that has been stored through a ViewState Key when a button clicked  PostBack to the server and Output the value.



Solution:
namespace MaintainingStateWithStateview
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState.Add("MyValue", "Tolu");
           
            }

        }

        protected void addButton_Click(object sender, EventArgs e)
        {
           string value = ViewState["MyValue"].ToString();
            resultLabel.Text = string.Format("MyValue key has {0} as it's value", value);
       
        }
    }
}











Now I will explain these lines of code
  1. Namespace is the code block that takes in all our lines of code, in this case namespace contains class(es) and method(s).
  1. public partial class Default : System.Web.UI.Page , as the name implies , its the class that our code contains.
  1. protected void Page_Load(object sender, EventArgs e) is the page load event handler(method), this intiate the initial loading of our page. Now this method takes a conditional statement of If() something is true do nothing  and if not do something else .  ofcouse that code could be rewitten in this format:
        if(Page.IsPostBack)       
   {          
        // do nothing special          
    }          
     else           
 {              
     ViewState.Add("MyValue", "Tolu");         
  }

In this regards , Our page_load method will make use of this line of code only. WHY? well , since Our Add  button hasnt been clicked  from the page default loading so the page hasnt been posted Back, since PostBack Occur when a button is click and not from the default loading.ViewState.Add("Key" , "Value");  --- ViewState Add a value to itself through it's key. Which in otherway round that value could be retrieve by access ViewState["Key"], in this case ViewSate["MyValue"] has Tolu as it's Value.   

 4.    protected void addButton_Click(object sender, EventArgs e)- this is a method that PostBack to the server and once clicked it Ignores the default page load and execute codes that are presently insides its block.


  •             string value = ViewState["MyValue"].ToString();  -- Here I made a local string with a variable name "value"  this value is initalize with ViewState["MyValue"] since ViewState["MyValue "] is a generic object that stores our ("Tolu") value  a cast  to a string with a helper method ToString() is needed. What this line of code says is everything  ViewState["MyValue"] has, store it in my value variable.


  •             resultLabel.Text = string.Format("MyValue key has {0} as it's value ", value);  ---- Output whatever  ViewState["MyValue"] has been passed back to my string variable named  value.

Example 2:

There is a default amount of money from a player added to  a view state and after the player makes some bets. I need to subtract the lost from the players default money and if the player wins I need to add the winnings to the players money this process continues.
In this case declaring an int variable of playersMoney is not going to work rather:
we could use a ViewState.Add object.
Solution :
let say the default value is £200.
// adding 200 to viewstate
ViewState.Add("playersMoney", 200)
// now call viewstate to give us this value
int playersMoney = (int)ViewState["playersMoney"] // a cast to int is needed here on the viewstate is  a generic object.
//now if the player bet £20 and wins £40 then :
playersMoney -= bet; // The players bet money off from the players total Money
playersMoney += win; // The player amount of gain at this time extra £20
// Add  winnings or bets back to the viewstate:
ViewState["playersMoney"] = playersMoney;
string result =  string.Format("Players Money:{0:C}", ViewState["playersMoney"]);
 Then If you will like to check if a particular player still have money to continue betting then you can check with:
if ((int)ViewState["playersMoney"] !=0)
{
  //Continue betting.
}
else
{
   // else add money to your act.
}

     

     


No comments:

Post a Comment

Note: only a member of this blog may post a comment.