Hey everyone, not sure if this is handled by the framework or not and if so please let me know as I would like to stick to what is presented in the book as much as possible if it is there.
Prob:
I have a OtM (One to Many) relationship between two tables. I was trying to figure out how to get the Id from the parent into each new child. I tried creating the object in the child class but that resulted in errors and when I did get it to work the Id was 0.
I then used the querystring to pass the value but this resulted in a max of two tables being able to be created. Think about it and you know why.
This put me at a loss as I knew there are OtM used through out the book but they are being passed via a control or based on CurrentUser.ID.
Solution;
Again this may not be the best solution but it works for me. Part of the credit goes to Ronnie, for providing the GetQueryStringValue method. What he did actually sparked the idea for this solution. Thanks
What I did was use the Viewstate to get this from the Parent. Normally the answer is no you cant use the VS from a previous page once it is out of scope. However I have managed to do it.
- From your Parent Page, create a link that goes to your Child List Page using the EncryptQueryString
- On your list page, create a view state that takes the decrypted string value. I placed my in Page_Load
Code:
ViewState["ViewState1"] = GetDecryptedValue("id").ToString();
- Create a StateBag Method to return ViewState
Code:
publicStateBag ReturnViewState()
{
return ViewState;
}
- Modify your Master_AddButton_Click as follows: Server.Transfer allows you keep VS intact
Code:
void Master_AddButton_Click(object sender, EventArgs e)
{
//Response.Redirect("Page2.aspx" + EncryptQueryString("id=0"));
Server.Transfer("Page2.aspx" + EncryptQueryString("id=0"));
}
- On Page2.aspx add this method
Code:
privateStateBag PreviousPageViewState
{
get
{
StateBag returnValue = null;
if (PreviousPage != null)
{
Object objPreviousPage = (Object)PreviousPage;
MethodInfo objMethod = objPreviousPage.GetType().GetMethod("ReturnViewState");
return (StateBag)objMethod.Invoke(objPreviousPage, null);
//foreach (MethodInfo objMethodInfo in obj.GetType().GetMethods())
//{
// if (objMethodInfo.Name == "ReturnViewState")
// {
// return (StateBag)objMethodInfo.Invoke(obj, null);
// }
//}
}
return returnValue;
}
}
- In Page_Load add the following. This only works in Page_Load. You can use what ever page control to store the value. This is the part I dont like any ideas for a more clean solution are welcome
Code:
if (PreviousPage != null)
{
if (PreviousPageViewState != null)
{
Label1.Text = PreviousPageViewState["ViewState1"].ToString();
}
}
- Now you can get the Parent Id after leaving the Parent Page.
Well that is what I came up with. Again if someone can offer something that is more inline with the book please respond. Other than that I hope everyone can find value in this.
Thanks
DJ