Wednesday, 4 April 2012

Passing data from one webpage to another in Asp.net using Cross-Page Posting

Cross-page posting is used when data is collected on one web page and processed on another web page. To do this following steps should be followed:

1. Create a aspx page to collect data from user and name it as GetData.aspx. This form should look something like this:


2. Set the post back url of the SUBMIT button to the second page (DisplayData.aspx)


3. Code the cs file of GetData

public partial class GetData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    //code for SUBMIT button
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //if user has selected a picture then save it into the Images folder
        if (FileUpload1.HasFile)
            FileUpload1.SaveAs(MapPath("~/Images/" + FileUpload1.FileName));
        String filename = FileUpload1.FileName;
    }

    //define public properties which return information collected on the data collection page
    //property to return the name of person
    public string PageData1
    {
        get { return txtName.Text; }
    }

    //property to return the gender of person
    public string PageData2
    {
        get
        {
            if (RadioButtonMale.Checked)
                return RadioButtonMale.Text;
            else
                return RadioButtonFemale.Text;
        }
    }

    //property to return the address of person
    public string PageData3
    {
        get { return txtAddress.Text; }
    }

    //property to return the phone of person
    public string PageData4
    {
        get { return txtPhone.Text; }
    }

    //property to return the email of person
    public string PageData5
    {
        get { return txtEmail.Text; }
    }

    //property to return the photo of person
    public string PageData6
    {
        get { return FileUpload1.FileName; }
    }
}

4. Create a aspx page to process GetData.aspx's data and display it, name this aspx page as DisplayData.aspx, this page should look something like this:


5. Set the PreviousPageType directive on the processing page to point to the data collection page.

6. Code the cs file of DisplayData

public partial class DisplayData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblShowName.Text = PreviousPage.PageData1;
        lblShowGender.Text = PreviousPage.PageData2;
        lblShowAddress.Text = PreviousPage.PageData3;
        lblShowPhone.Text = PreviousPage.PageData4;
        lblShowEmail.Text = PreviousPage.PageData5;
        Image1.ImageUrl = "~/Images/" + PreviousPage.PageData6;
    }
}

7. Now when you run this application you will get something like this:




No comments:

Post a Comment