The approach you're looking for is some kind of databinding mechanism that binds the values of an object (you may load from the db if it already exists) to your asp.net webform.
Basically you'd have the folling:
- You display an empty webform with fields (i.e. textboxes) for the properties of your object
- The user will fill the the form and press save
- Then the postback will happen. On the PageLoad you can detect whether this is a postback with
Page.IsPostback
and if so, you create a new object and fill it with the values the user entered.
- In the OnClick of your button, you call the appropriate BL method for storing it down to the DB
This would look like (I'm writing it out of my head without a compiler, so take care :) )
public partial class MyPage : Page
{
private Person myPersonObj;
protected void Page_Load(...)
{
if(!Page.IsPostback)
{
//this is not a postback, so you may load an object based on an ID (i.e. in QueryString or create a new one
myPersonObj = new Person();
}
else
{
//it is a postback, so unbind the values
myPersonObj = new Person();
Unbind(); //the myPersonObj will be filled, the values are managed by ASP.net in the ViewState
}
}
//caution, overriding Page.DataBind()
private override void DataBind()
{
textBoxFirstname.Text = myPersonObj.FirstName;
...
}
private void Unbind()
{
myPersonObj.FirstName = textBoxFirstname.Text;
}
protected void btnSubmit_OnClick(...)
{
if(Page.IsValid)
{
Save();
}
}
private void Save()
{
//ideal layering with Interfaces
IPersonBL personBL = MyBLFactory.Get<IPersonBL>();
personBL.SavePerson(myPersonObj); //call the BL for further validation and then persisting
}
}
What I wanted to add yesterday, but forgot since I had to hurry:
You can as well store your objects in the ViewState or Session as others described, but I have experienced that it should be done as rare as possible due to the following "disadvantages" (from my point of view):
- Your objects need to be serializable
- Storing in the ViewState will drammatically increase the size of your page and thus slowing down the loading of your page. Note the ViewState is transferred to the client and back each time a "postback" occurs. If that's the only possibility and you're experiencing performance problems you may consider trying this (but this should be the exception!!)
- Storing Objects in your session may put the load on the server-side, consuming the memory there. You should be careful in storing objects in your session and possibly also care about destruction of those objects if you know you don't need them any more.
The advantage of the "databinding" approach I described is that you don't have these problems, with the "disadvantage" of having a new fresh object each time. You therefore have to take care of handling your object state, i.e. manually keeping id's through roundtrips etc..