Some Developer
Some Developer

Reputation: 239

Access POST form data and write it in an xml file?

So I've been looking for a good solution everywhere but did not find anything useful. So basically what I want to do is to access the (post) form data with C# in the codebehind of an .aspx web form and then write that data into a xml (and also create the xml of course).

Let us say I have something like this:

<asp:Content runat="server" ContentPlaceHolderID="pageContent">

    <form id="form1" method="post" name="contact" action="contact.aspx">
       (...)
       <input type="button" value="Send" id="submit"
    </form>

</asp:Content>

now I guess it doesn't matter what's inside the form.

I found this xml writer class --> http://msdn.microsoft.com/de-de/library/system.xml.xmlwriter(v=VS.80).aspx, but I really just don't know where to start.

If anybody can help me with that or maybe this question has been answered here before and I just overlooked it, so you could link me there I'd be grateful for that.

thanks in advance!

Upvotes: 2

Views: 2706

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039110

You cannot use the <form> tag in ASP.NET WebForms because there's already a <form runat="server"> and HTML forms cannot be nested. So here you have 2 different tasks to accomplish:

  1. Send POST data to Contact.aspx
  2. Use the POST data in Contact.aspx to generate a XML file

So let's tackle those two separate tasks starting with the first one. Let's suppose that you have a Default.aspx web form in which the user will enter some input data:

<div>
    First name: <asp:TextBox ID="EdtFirstName" runat="server" />
</div>
<div>
    Last name: <asp:TextBox ID="EdtLastName" runat="server" />
</div>

<asp:LinkButton ID="BtnSubmit" runat="server" PostBackUrl="Contact.aspx" Text="Generate XML" />

and in the code behind you would expose the 2 values:

public partial class _Default : System.Web.UI.Page
{
    public string FirstName
    {
        get { return EdtFirstName.Text; }
    }

    public string LastName
    {
        get { return EdtLastName.Text; }
    }
}

Now we could move on to implementing the second task of generating the XML file inside Contact.aspx:

public partial class Contact : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var page = (Page.PreviousPage as _Default);
        if (page != null)
        {
            var xml = new XDocument(
                new XElement(
                    "user",
                    new XElement("firstName", page.FirstName),
                    new XElement("lastName", page.LastName)
                )    
            );
            var file = Server.MapPath("~/test.xml");
            xml.Save(file);
        }
    }
}

Upvotes: 2

Related Questions