I've been mucking around with (D)LINQ all week (this will probably be its own series of posts if I get around to it) and as a part of this, I've been reading a lot of blogs (no-thanks to Microsoft's lack of implementation demos). Something I've noticed in a few entries is storing a variable available in the Requests body in the pages ViewState.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Request["id"]))
Id = Convert.ToInt32(Request["Id"]);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Controls.Add(new LiteralControl(string.Format("Id is {0}", Id)));
}
protected int Id
{
get
{
object o = ViewState["Id"];
return (o == null ? -1 : (int)o);
}
set { ViewState["Id"] = value; }
}
}
I can think of a few reasons why this is unnecessary:
- During any ASP.NET client-server interaction on this page, the exact URL will be used hence the data will always be available in the HttpRequest object
- Adds to viewstate (obviously) = increased transit size and time-to-serve
- Serialization/deserialization on every hit
Since it's available on every request, don't bother yourself with the viewstate, save a few lines of code and just grab it from the Request during the pages Load event:
public partial class _Default : System.Web.UI.Page
{
int Id;
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request["id"]))
Id = Convert.ToInt32(Request["Id"]);
if (!Page.IsPostBack)
{
// Do stuff...
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Controls.Add(new LiteralControl(string.Format("Id is {0}", Id)));
}
}
As an added bonus, the HttpRequest is available much earlier in the page lifecycle (before the viewstate) permitting initial events access to this (you would of course need to parse it much earlier too).
0 comments:
Post a Comment