Cross-Page Posting in asp.net using c#

In this tutorial you will learn how to perform cross-page posting in asp.net using c#. In asp.net we normally use web forms that post back themselves only. Under some circumstances, you may need to post one page to another page. For instance, you might be creating a multi-page form that gets different information on each page. In that scenario, you can configure certain controls (those that implement the IButtonControl interface, like Button control) on the page to post to a different target page. This is called as cross-page posting. Cross-page posting is configured for individual controls. you can create a page that posts to different pages depending on which button the user clicks.

In this post we will cover all the aspects. No need to take tension whether pages are using masterpage or not. When you configure a page for cross-page posting, you frequently want to collect information from the source page. This might include the information from controls on the page, the information being posted by the browser, as well as public properties of the source page. Let's have a look over different techniques of cross-page posting. This post is little bit lengthy than my other posts as it is covering all the aspects but guaranteed very helpful post.

Cross-Page Posting in asp.net using c#

1) Server.Transfer()

Server.Transfer() transfers user from one page to another with the complete data of previous page. It is a partial Cross-Page posting technique; I am saying this technique partial because while posting from one page to another the url doesn’t change. The receiving web page has several options to get the data from the first web page. All of these options use the new property PreviousPage() of page class. PreviousPage() represents the originating page in transfer and cross page post back operations. If the source page and target page are in the same ASP.NET application, the PreviousPage() property in the target page contains a reference to the source page. (If the page is not the target of a cross-page posting, or if the pages are in different applications, the PreviousPage() property is not initialized.) By default, the PreviousPage() property is typed as Page. Using the reference in the PreviousPage() property, you can search for controls on the source page and get their value. You typically do this with the built-in FindControl(String) method. Let’s have a look over the sample code used for demo


SourcePage.aspx
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br/><br/>
<asp:Button ID="btn_Submit" runat="server" Text="Submit" OnClick="btn_Submit_Click"/>
SourcePage.aspx.cs
protected void btn_Submit_Click(object sender, EventArgs e)
{
Server.Transfer("TargetPage.aspx");
} 
TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox txtName = PreviousPage.FindControl("txtName") as TextBox;
  if (txtName != null)
  {
   // your rest of code will come here
  }
}
Note

If your .aspx page (SourcePage.aspx) is using masterpage then code in Page_Load() event of TargetPage.aspx.cs will be

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
ContentPlaceHolder mpContentPlaceHolder;
TextBox txtName;

/* The id of <asp:ContentPlaceHolder> being used in masterpage like
<asp:ContentPlaceHolder ID="MasterPageContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>*/

mpContentPlaceHolder = (ContentPlaceHolder)PreviousPage.Master.FindControl("MasterPageContentPlaceHolder");

//Now we are searching textbox in mpContentPlaceHolder
if (mpContentPlaceHolder != null)
{
txtName = (TextBox)mpContentPlaceHolder.FindControl("txtName");

  if (txtName != null)
  {
  //Your code will come here
  }

}

}

}
The FindControl(String) method finds controls in the current naming container. If the control you are looking for is inside another control (typically, inside a template), you must first get a reference to the container and then search the container to find the control you want to get.

Server.Transfer() has one major drawback and that is while using the Server.Transfer() approach the url in the browser does not change.

The browser thinks it has been posted back and fetches the content of the first web form, so history and bookmarking suffered.

2) Getting Public Property Values from the Source Page

In the target page of a cross-page posting, you can also get the values of public members of the source page. The most common scenario is that the source page defines public properties and you want to get their values on the target page.

Note
It is strongly recommended that you expose only the information you need as public properties to reduce the amount of information available to potentially malicious users. To get public members of the source page, you must first get a strongly typed reference to the source page.

You can do so via include an @ PreviousPageType directive in the target page, which allows you to specify the source page, as in this example:
<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>
When this directive is included, the PreviousPage() property is strongly typed to the class of the referenced source page. As a consequence, you can directly reference public members of the source page.

SourcePage.aspx
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br/><br/>

<asp:Button ID="btn_Submit" runat="server" Text="Submit" PostBackUrl="~/TargetPage.aspx"/>
SourcePage.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

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

}

public String FirstName
{
get
{
return txtName.Text;
}
}
}

The above code example shows that source page containing a public property named FirstName that exposes the value of a TextBox control named txtName.

Note
Properties on the source page that are created primarily to expose values for cross-page posting are usually read-only properties. Although the source page can contain public read/write properties, setting a source page property from the target page property generally has no purpose, because the value will not be persisted.


TargetPage.aspx
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="TargetPage.aspx.cs" Inherits="TargetPage" Title="Target Page" %>

<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

<asp:Content ID="Content1" ContentPlaceHolderID="WebDynamicWebContentsPlaceHolder" Runat="Server">
<asp:TextBox ID="txtMyName" runat="server" EnableTheming="false" Text="First Name will come here"></asp:TextBox>
</asp:Content>

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{

if (PreviousPage != null)
{
txtMyName.Text = PreviousPage.FirstName;
}
}

If the target page contains a PreviousPageType directive that refers to the source page, you can get the source page's FirstName property using code given above.

3) PostBackUrl Property

The working of PostBackUrl is the same as Server.Transfer() but using this technique the url changes when we redirect from one web page to another. For transferring data from one web form/web page to another web form/web page this technique is quite handy. It’s quite simple as well. You just have to use the PostBackUrl property of asp:button that will postback the form data to the webpage mentioned in the PostBackUrl property. Let’s have a look over the example

SourcePage.aspx

<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br/><br/>

<asp:Button ID="btn_Submit" runat="server" Text="Submit" PostBackUrl="~/TargetPage.aspx"/>

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)

{

if (PreviousPage != null)

{

TextBox txtName = PreviousPage.FindControl("txtName") as TextBox;

if (txtName != null)

{

// your rest of code will come here

}

}

}
Note: - If your .aspx page (SourcePage.aspx) is using masterpage then code in Page_Load() event of TargetPage.aspx.cs will be

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)

{

if (PreviousPage != null)

{

ContentPlaceHolder mpContentPlaceHolder;
TextBox txtName;

//The id of <asp:ContentPlaceHolder> being used in masterpage like
/* <asp:ContentPlaceHolder ID="MasterPageContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>*/

mpContentPlaceHolder = (ContentPlaceHolder)PreviousPage.Master.FindControl("MasterPageContentPlaceHolder");

//Now we are searching textbox in mpContentPlaceHolder
if (mpContentPlaceHolder != null)
{
txtName = (TextBox)mpContentPlaceHolder.FindControl("txtName");
if (txtName != null)
{
}
}

}

}
Note

If you are using the PostBackUrl property of the asp button then don’t fire the onClick event of that asp button.

But this approach is still not very much effective if we want to assign the PostBackUrl property of the asp button after some certain if/else checks. We can set the page name in PostBackUrl by using c# code on page load event of page but what should we do if we want to set the page name in PostBackUrl using client side javascript after getting some user interaction and then have to decide which page user should redirect. To handle this scenario and to receive form data with more simple way the next technique is very handy and effective. You can call this 3) custom cross-page posting technique.

Custom cross-page posting technique

SourcePage.aspx
<script language="javascript">
<!--
function NoPostBack(sFormAction)
{

var _Post="Default.aspx";
var checkPoint = document.getElementById("<%=txtName.ClientID %>").value;
alert(checkPoint);
if (checkPoint == "Adeel")
{
_Post = "TargetPage.aspx";
document.forms[0].action = _Post;
document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
}
else if (checkPoint == "Maaz")
{
_Post = "anotherpage.aspx";
document.forms[0].action = _Post;
document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
//document.forms[0].target = "_blank";
}
else
{
return false;
}


}-->
</script>

<p>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

</p>

<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" EnableTheming="false" OnClientClick="NoPostBack(this.id);"/>

</p>
Using javascript custom function we are performing cross-page posting. document.forms[0].target = "_blank" means the next page will be open in new window. If you don’t want to open next page in new window then comment this line of code. In this above example, sourcepage.aspx is relying on masterpage. Now let’s have a look over the Target page that will get the value of this form.

TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{

if (Request.Form != null && Request.Form.Count >0)
{
Label1.Text = Request.Form["ctl00$ContentPlaceHolder1$txtName"].ToString();
}
}

Hay, you are surprised to see this ctl00$MyWebsiteWebContentsPlaceHolder$txtName instead of txtName, now let me explain. In this example The sourcepage.aspx is using masterpage and when I post the form data then after rendering, the id of textbox changes from txtName to ctl00$MyWebsiteWebContentsPlaceHolder$txtName . The new id ctl00$MyWebsiteWebContentsPlaceHolder$txtName contains the reference of masterpage. See the image below.


cross-page posting using masterpage

But if your page is not relying on masterpage then you will get same id of textbox which is txtName in Target.aspx page like mentioned in below image.


cross-page posting without using masterpage

So these are the ways to perform cross-page posting in asp.net using c#. I hope you will find this article very handy.
Read more...

How to fire the client side onclick event of link button inside gridview in asp.net using jquery

In this tutorial you will learn how to fire the client side onclick event of link button inside gridview in asp.net using jquery. I have already taught you about how to fire the server side click event of gridview link button in asp.net using c#. The reason that's why I am writing this article is that if we can do the same work through the client side then there is no need to fire the link button's server side click event because the client side method is always speedy.


How to fire the client side onclick event of link button inside gridview in asp.net using jquery


jquery code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
type="text/javascript" charset="utf-8"></script>

<script type="text/javascript">
jQuery(function()
{
//debugger;
jQuery("table[id$='GridView1'] td:nth-child(2)").live('click',function(event){window.location="nextpage.aspx?firstname="+jQuery(event.target).text();});
});
</script>

.aspx code
<asp:GridView ID="GridView1" runat="server" EnableTheming="false" AutoGenerateColumns="false" GridLines="None" Width="100%">

<Columns>

<asp:TemplateField HeaderText="Sr#" HeaderStyle-Width="10%" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblSrNo" runat="server" EnableTheming="false" Text='<%# Bind("SrNo")%>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

<asp:TemplateField HeaderText="First Name" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="lnkFirstName" runat="server" EnableTheming="false" Text='<%# bind("firstName") %>'></asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>

<asp:TemplateField HeaderText="Last Name" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" EnableTheming="false" Text='<%# Bind("LastName")%>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>

</Columns>

</asp:GridView>

You have to include the jquery file in your .aspx page and then copy/paste the above mentioned javascript function and change it according to your need.

jQuery's Selectors allow you to select DOM elements so that you can apply functionality to them using jQuery's operational methods. jQuery uses CSS 3.0 syntax (plus some extensions) to select single/multiple elements in a document. Using CSS syntax you can select elements by their id, CSS class, attribute filters, by relationship to other element and even filter conditions that can be chained together.

Now let's understand the jquery code use in this example. td:nth-child(2) means get the all second column TD elements of gridview. nth means all elements and then using built-in live() function of jquery I am binding it's client side onclick event and then I have written a code that will be executed whenever client side onclick event will be fired. As you know when asp page renders then <asp:Gridview> is converted into table that's why I am using td:nth-child(2).

jQuery(event.target).text()
is getting the text of link button and then I am redirecting user to nextpage.aspx.

So this is the way to fire the clientside onclick event of link button inside gridview in asp.net using jquery.

Read more...

How to generate the row number in gridview in asp.net

In this asp.net tutorial you will learn how to generate the row number/serial number in gridview in asp.net. These days it is common requirement to show row number in report so that the user can come to know how many records/rows the gridview have. This tutorial will teach you two methods to generate or display the row number in gridview. Let's have a look over it.

generate row number

How to generate the row number in gridview in asp.net

generate_row_number.aspx

Method 1:-
<asp:GridView ID="GridView1" runat="server" EnableTheming="false" AutoGenerateColumns="false" GridLines="None" Width="100%" CssClass="textTD">

<Columns>
<asp:TemplateField HeaderText="Sr No" HeaderStyle-Width="5%" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="First Name" HeaderStyle-Width="10%" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" EnableTheming="false" Text='<%# Bind("first_name")%>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

<asp:TemplateField HeaderText="Last Name" HeaderStyle-Width="10%" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" EnableTheming="false" Text='<%# Bind("last_name")%>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

</Columns>
</asp:GridView>

I prefer this method as you don't need to code extra in .cs side, also you don't need to write extra code when you want AllowPaging=”true” in gridview. <%# Container.DataItemIndex + 1 %> does all things.

Method 2:-

generate_row_number.aspx
<asp:GridView ID="GridView1" runat="server" EnableTheming="false" AutoGenerateColumns="false" GridLines="None" Width="100%" CssClass="textTD" OnRowDataBound="GridView1_RowDataBound">

<Columns>
<asp:TemplateField HeaderText="Sr" HeaderStyle-Width="5%" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblSerialNo" runat="server" EnableTheming="false"></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />

</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" HeaderStyle-Width="10%" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" EnableTheming="false" Text='<%# Bind("first_name")%>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

<asp:TemplateField HeaderText="Last Name" HeaderStyle-Width="10%" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" EnableTheming="false" Text='<%# Bind("last_name")%>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>

generate_row_number.aspx.cs
public partial class Reports_generate_row_number : System.Web.UI.Page
{
int serialNo=1;
protected void Page_Load(object sender, EventArgs e)
{
//Some code will come here
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{

if (!String.IsNullOrEmpty(((Label)e.Row.FindControl("lblFirstName")).Text))
{
Label lblSerial = (Label)e.Row.FindControl("lblSerialNo");
lblSerial.Text = serialNo.ToString();
serialNo = serialNo+1;

}
}

}

}
This method is little bit lengthy as compare to first method because you have to write code in .cs side as well.

You have to fire the onRowDataBound event of GridView. You have to put a label in the gridview and give some id to that label, in my case it is lblSerialNo and then at .cs side you have to declare a global int variable with default value 1 and then in RowDataBound event you have to increment the value of that global int variable by 1 and then assign it to lblSerialNo and that’s it. This method is useful when you want to write your own method for pagination in gridview. So these are the ways to generate the row number in asp.net using c#.
Read more...