This post is gives you some solutions for 10 real life application problems in asp.net:
- How to interrupt postback from client side?
- How to avoid duplicate form tag error?
- How to ask confirmation on page unload event?
- How to persists data from client to server side?
- How to bind a dropdownlist from a datatable?
- How to do a multi-line gridview?
- How to serialize/deserialize object in XML?
- How to register JavaScript from server side?
- How to enable disable validation from client side?
- How to pass information between one page to another?
You can download all samples
Question 1: How to interrupt postback from client side?
In asp.net, the button has two click events, OnClick which call a server side method and OnClientClick which call client side method. If you click the button and you want to do only client side action, so you don’t want to have a postback, you have to return false OnClientClick.
It can be interesting if you want to make some checks from client side (in this example, if there is an item selected), or if you want to ask confirmation to end user.
Example:
<script type="text/javascript">
function confirmDelete() {
//Check if there is a selected item
var selectedItem = document.getElementById("<%= lstItems.ClientID %>").value;
if (selectedItem != null && selectedItem != '') {
return confirm('Do you really want to delete this item?');
}
else {
//Return false -> no postback
return false;
}
}
</script>
<asp:ListBox runat="server" ID="lstItems">
<asp:ListItem Selected="True">Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
</asp:ListBox>
<br />
<asp:LinkButton runat="server" ID="lnkDelete" Text="Delete" OnClick="lnkDelete_Click" OnClientClick="return confirmDelete()"></asp:LinkButton>
To get the full source code click here.
Question 2: How to use form tag in asp.net page using javascript?
Sometimes you need to use a form tag to submit something (for example PayPal information), but in asp.net you can’t add duplicate form tag in a page. A way to avoid this problem is using JavaScript to generate and submit a form. Here is an example of PayPal button:
<script type="text/javascript">
function post() {
//Add your PayPal account information here
var myForm = document.createElement("form");
myForm.method = "post";
myForm.action = "https://www.paypal.com/cgi-bin/webscr";
document.body.appendChild(myForm);
myForm.submit();
document.body.removeChild(myForm);
return false;
}
</script>
<asp:Button runat="server" ID="btnPayPal" OnClientClick="return post();" Text="PayPal" />
To get the full source code click here.
Question 3: How to ask confirmation on page unload event ?
Sometimes, the user need to perform an action completely and to save his action after. In this case, the user need to be sure that his work is saved before leaving the application. In term of programming, you need to track the unload event of the page and allow postback only if the user click the save button. Here is an example to this:
<script type="text/javascript">
var postback = false;
window.onbeforeunload = confirmExit;
function confirmExit() {
if (postback == true) {
event.cancelBubble = true;
}
else
return 'Please save or cancel before leaving this page.';
}
</script>
<asp:Button runat="server" ID="btnDoRegisteredPostback" Text="DoRegisteredPostBack"
OnClientClick="postback=true;return true;" />
<asp:Button runat="server" ID="btnDoPostback" Text="LeavePage"
onclick="btnDoPostback_Click" />
To get the full source code click here.
Question 4: How to persist data from client side to server side?
As you know everything you change in JavaScript (value, style, …) is not applied to server side. The only way to maintain the page state from the client side to the server side is to use Hidden Fields. Here is a sample in which I change the textbox color via JavaScript and I save state with a hidden field.
Client side code: Set hidden field with textbox color value
<script type="text/javascript">
function changeColor() {
var txtMyTextBox = document.getElementById("txtMyTextBox");
var hifMyTextBoxColor = document.getElementById("hifMyTextBoxColor");
var color = '#' + getRandomColor();
txtMyTextBox.style.backgroundColor = color;
hifMyTextBoxColor.value = color;
return false;
}
function getRandomColor() {
colors = new Array(14)
colors[0] = "0"
colors[1] = "1"
colors[2] = "2"
colors[3] = "3"
colors[4] = "4"
colors[5] = "5"
colors[5] = "6"
colors[6] = "7"
colors[7] = "8"
colors[8] = "9"
colors[9] = "a"
colors[10] = "b"
colors[11] = "c"
colors[12] = "d"
colors[13] = "e"
colors[14] = "f"
digit = new Array(5)
color = ""
for (i = 0; i < 6; i++) {
digit[i] = colors[Math.round(Math.random() * 14)]
color = color + digit[i]
}
return color;
}
</script>
<asp:HiddenField ID="hifMyTextBoxColor" runat="server" />
<asp:TextBox runat="server" ID="txtMyTextBox"></asp:TextBox>
<asp:Button runat="server" ID="btnChangeColor" Text="ColorTextBox" OnClientClick="return changeColor();" />
<asp:Button runat="server" ID="btnSaveWithColorState" Text="Keep Color State & Save"
OnClick="btnSaveWithColorState_Click" />
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" />
Server side code: Set textbox color with hidden field value
protected void btnSaveWithColorState_Click(object sender, EventArgs e)
{
txtMyTextBox.BackColor = Color.FromName(hifMyTextBoxColor.Value);
//Your save method here
}
For more information about ‘ASP.NET State Management Recommendations’:
http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx
To get the full source code click here.
Question 5: How to bind a dropdownlist from a datatable?
To bind dropdown list items with data table use the DataValueField and DataTextFieldProperty.
ddlFromDataTable.DataSource = dt;
ddlFromDataTable.DataValueField = "ProductID";
ddlFromDataTable.DataTextField = "ProductName";
ddlFromDataTable.DataBind();
To get the full source code click here.
Question 6: How to do a multi-line gridview?
Sometimes, you need to display a lot of information in a grid view but your page size is not extensible. In this case, a solution can be to split the row in two lines. To do this, you have to customize your item by using an template field.
<asp:TemplateField HeaderText="Login/Password">
<EditItemTemplate>
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Login") %>'></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
</td>
</tr>
</table>
</EditItemTemplate>
<ItemTemplate>
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Login") %>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Password") %>'></asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
To get the full source code click here.
Question 7: How to serialize/deserialize object in XML?
To serialize and deserialize object easily, you can use this ObjectSerializer static class:
public static class ObjectSerializer
{
public static string Serialize<T>(T obj)
{
// Assuming obj is an instance of an object
XmlSerializer ser = new XmlSerializer(typeof(T));
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, obj);
return sb.ToString();
}
public static T Deserialize<T>(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
//Assuming doc is an XML document containing a serialized object and objType is a System.Type set to the type of the object.
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(typeof(T));
object obj = ser.Deserialize(reader);
// Then you just need to cast obj into whatever type it is eg:
T myObj = (T)obj;
return myObj;
}
}
To get the full source code click here.
Question 8: How to register JavaScript from server side?
If you want to register JavaScript from the client side you just have to know these 2 Page methods:
- Page.ClientScript.IsClientScriptBlockRegistered: Check if the script is already registered.
- Page.ClientScript.RegisterClientScriptBlock: to register your script.
Here is a concrete example:
//If the script is not already registered
if (!Page.ClientScript.IsClientScriptBlockRegistered("MyAlertKey"))
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='javascript'>");
sb.Append("function alertHello() {");
sb.Append("alert ('Hello world!');");
sb.Append("return false;");
sb.Append("}");
sb.Append("</script>");
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyAlertKey", sb.ToString());
}
if (!IsPostBack)
{
btnHello.OnClientClick = "return alertHello();";
//btnHello.Attributes.Add("onclick", "javascript:return alertHello();");
}
To get the full source code click here.
Question 9: How to enable disable validation from client side?
Sometimes, when you are doing checks from client side, you need to disable validation, for example depending a dropdown list value. to perform this task you need to use the ValidatorEnable client function. here is a full example:
<script type="text/javascript">
function setValidationStatus() {
var enableValidation = !document.getElementById('<%=cbxDisableValidation.ClientID %>').checked;
ValidatorEnable(document.getElementById('<%=rfvValidateUser.ClientID%>'), enableValidation);
}
</script>
<asp:CheckBox ID="cbxDisableValidation" runat="server" Checked="false" Text="DisableValidation" />
<asp:TextBox ID="txtUser" runat="server" ValidationGroup="SaveUser"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvValidateUser" runat="server" ErrorMessage="Cannot be empty!"
ValidationGroup="SaveUser" ControlToValidate="txtUser" Display="Dynamic"
SetFocusOnError="True" Enabled="false">*</asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" Text="Save" ValidationGroup="SaveUser"
OnClientClick="setValidationStatus();" onclick="btnSave_Click" />
In this example if cbxDisableValidation is checked then I disable the validation.
To get the full source code click here.
Question 10: How to pass information between one page to another?
Passing parameters from one page to another is a very common task in Web development. In asp.net 2.0, you can simply add a button with a PostBackUrl properties containing the URL of the page to post.
In the first page:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" PostBackUrl="~/Question10b.aspx" />
In the second page:
<%= Request.Form["TextBox1"].ToString() %>
To get the full source code click here.