Wednesday, November 28, 2012

POST Method in ASP.NET

What we are going to achieve is to pass the text on a label in a Web page to another page through POST method.

There are several methods of passing data between pages in ASP.NET like GET method, Post method and Sessions

Get method - Passing data embedded in URL
Post method - Passing data embedded in form body
Sessions - Assign data to a session and retrieve from another page

In this post i'm going to give an example of passing data using POST method.

We have to lables "lblUserName" and "lblPassword" we use POST method to send this data to next page. Through the JavaScript code we assign the values in labels to the hidden fields. Finally we call the JavaScript function of Button1 ClientClick event.

<html xmlns="">

<head runat="server">
    <style type="text/css">
    <script type="text/javascript">
        function LoadValues() {
            form1.hUserName.value = document.getElementById('lblUserName').innerHTML;
            form1.hPassword.value = document.getElementById('lblPassword').innerHTML;
    <form id="form1" runat="server" method="post" >
        <asp:Label ID="lblUserName" runat="server" CssClass="hide" Text="chamara" ></asp:Label>
        <asp:Label ID="lblPassword" runat="server" CssClass="hide"  Text="123"></asp:Label>
        <input type="hidden" name="hUserName" value=""/>
        <input type="hidden" name="hPassword" value=""/>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="LoadValues();" PostBackUrl="~/Default.aspx" />

On Button1 click user will be redirected to the Default.aspx page and on the page load event of Default.aspx we can retrieve the values posted from the previous page.

protected void Page_Load(object sender, EventArgs e)

You should see the values "chamara" and "123" printed on the Default.aspx page.

No comments:
Write comments
Recommended Posts × +