using SESSIONS passing values to another page - c#

I am stuck on passing values from a form on one page to (confirm.aspx) another page. Would someone help me out with this? I am not looking for some one to code my program because I have done much of the work already. Here is what I have, Default.aspx as three values that I need to pass to Confirm.aspx. This is what I have for the Default.aspx.
<form id="form1" runat="server">
<h1>Price quotation</h1>
<label>Sales price</label>
<asp:TextBox ID="txtSalesPrice" runat="server" CssClass="entry">100</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtSalesPrice" Display="Dynamic" ErrorMessage="RequiredFieldValidator" CssClass="validator">Required</asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtSalesPrice" Display="Dynamic" MaximumValue="1000" MinimumValue="10" Type="Double" CssClass="validator">Must be from 10 to 1000</asp:RangeValidator><br /><br />
<label>Discount percent</label>
<asp:TextBox ID="txtDiscountPercent" runat="server" CssClass="entry">20</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtDiscountPercent" Display="Dynamic" ErrorMessage="RequiredFieldValidator" CssClass="validator">Required</asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator2" runat="server" ControlToValidate="txtDiscountPercent" Display="Dynamic" MaximumValue="50" MinimumValue="10" Type="Double" CssClass="validator">Must be from 10 to 50</asp:RangeValidator><br />
<label>Discount amount</label>
<asp:Label ID="lblDiscountAmount" runat="server" CssClass="result" ></asp:Label><br /><br />
<label>Total price</label>
<asp:Label ID="lblTotalPrice" runat="server" CssClass="result" ></asp:Label><br /><br />
<asp:Button ID="btnCalculate" runat="server" Text="Calculate" OnClick="btnCalculate_Click" CssClass="button" />
<asp:Button ID="ConfirmButton" runat="server" CssClass="button" Text="Confirm" PostBackUrl="~/Confirm.aspx" OnClick="ConfirmButton_Click" />
<p><asp:Label ID="lblMessage" runat="server" EnableViewState="false" /></p>
</form>
Code Behind the Default.aspx
protected void ConfirmButton_Click(object sender, EventArgs e)
{
Session["Sales"] = txtSalesPrice.Text;
Response.Redirect("Confirm.aspx");
Session["Amt"] = lblDiscountAmount.Text;
Response.Redirect("Confirm.aspx");
Session["Total"] = lblTotalPrice.Text;
Response.Redirect("Confirm.aspx");
}
Confirm.aspx
<form id="form1" runat="server">
<h1>Quotation confirmation</h1>
<label>Sales price</label><asp:Label ID="lblSalesPrice" runat="server" CssClass="result"></asp:Label><%=Session["Sales"] %><br /><br />
<label>Discount amount</label><asp:Label ID="lblDiscountAmount" runat="server" CssClass="result"><%=Session["Amt"] %></asp:Label><br /><br />
<label>Total price</label><asp:Label ID="lblTotalPrice" runat="server" CssClass="result"><%=Session["Price"] %></asp:Label><br />
<h2>Send confirmation to</h2>
<label>Name</label>
<asp:TextBox ID="txtName" runat="server" CssClass="entry"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" CssClass="validator">Required</asp:RequiredFieldValidator><br />
<label>Email address</label>
<asp:TextBox ID="txtEmail" runat="server" CssClass="entry"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtEmail" Display="Dynamic" ErrorMessage="RequiredFieldValidator" CssClass="validator">Required</asp:RequiredFieldValidator><br />
<asp:Button ID="btnSubmit" runat="server" Text="Send Quotation" CssClass="button" OnClick="btnSubmit_Click" />
<asp:Button ID="btnReturn" runat="server" Text="Return" PostBackUrl="~/Default.aspx" CausesValidation="false" CssClass="button" OnClick="btnReturn_Click" />
<p><asp:Label ID="lblMessage" runat="server" ViewStateMode="Enabled" /></p>
</form>
If someone would take the time out and review what I have here. I would appreciate. There is nothing pertinent on the code behind on the Confirm.aspx.cs.

Code behind default.aspx
protected void ConfirmButton_Click(object sender, EventArgs e)
{
Session["Sales"] = txtSalesPrice.Text;
Session["Amt"] = lblDiscountAmount.Text;
Session["Total"] = lblTotalPrice.Text;
Response.Redirect("Confirm.aspx");
}
And you get value in another page like this
In .cs
txtSales.text = Session["Sales"];
In .aspx
<asp:TextBox ID="txtSales" runat="server" Text='<%# Session["Sales"] %>' >

Related

Custom Validator won't fire

I'm trying to force the user to choose to fill either the Photo or the Video Textbox using the CustomValidator but it's not working, I've tried searching around and from previous questions a lot of people instructed to add the ValidateEmptyText="true" property, I tried adding it but it still won't fire.
I'm using other RequiredFieldValidators which are operating normally.
This is my aspx code of the two fields:
<asp:Button ID="btn1" runat="server" Text="+"/>
<asp:TextBox runat="server" PlaceHolder="Photos" ID="pics" ValidationGroup="txt1"></asp:TextBox>
<br />
<asp:Button ID="btn2" runat="server" Text="+"/>
<asp:TextBox ID="vids" runat="server" PlaceHolder="Videos" ValidationGroup="txt1"></asp:TextBox>
<asp:CustomValidator runat="server" ErrorMessage="Please enter either a photo or a picture!" OnServerValidate="ValidateBoxes" ValidationGroup="txt1" ValidateEmptyText="true"></asp:CustomValidator>
This is my c# Validation method:
public void ValidateBoxes(object sender, ServerValidateEventArgs e)
{
if (string.IsNullOrEmpty(pics.Text) && string.IsNullOrWhiteSpace(vids.Text))
e.IsValid = false;
else
e.IsValid = true;
}
EDIT : This is one of the text boxes and it's validators from the output screen shots.
<asp:TextBox ID ="city_in" PlaceHolder ="Enter city" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="city_in" ErrorMessage="Please enter the city!" ForeColor="Red"></asp:RequiredFieldValidator>
EDIT: This is the whole aspx Code:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h1>
Creating An Event
</h1>
<br />
<h3>
Please Provide the information below
</h3>
<asp:TextBox ID ="city_in" PlaceHolder ="Enter city" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="city_in" ErrorMessage="Please enter the city!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:TextBox ID="date" runat="server" PlaceHolder ="Enter date" TextMode="Date" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="date" ErrorMessage="Please enter the date!" ForeColor="Red" ></asp:RequiredFieldValidator>
<br />
<br />
<asp:TextBox ID="desc" runat="server" PlaceHolder = "Description"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="desc" ErrorMessage="Please enter the description!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:TextBox ID ="entertain" runat="server" PlaceHolder ="Entertainer"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="entertain" ErrorMessage="Please enter the entertainer!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:TextBox ID ="viewer" runat="server" PlaceHolder ="ID"></asp:TextBox>
<br />
<br />
<asp:TextBox ID ="location" runat="server" PlaceHolder ="Location"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter the location!" ControlToValidate="location" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<p>
Please choose what type of Multimedia you would like to upload
</p>
<br />
<asp:Button ID="btn1" runat="server" Text="+"/>
<asp:TextBox runat="server" PlaceHolder="Photos" ID="pics" ></asp:TextBox>
<br />
<asp:Button ID="btn2" runat="server" Text="+"/>
<asp:TextBox ID="vids" runat="server" PlaceHolder="Videos"></asp:TextBox>
<asp:CustomValidator runat="server" ErrorMessage="Please enter either a photo or a picture!" OnServerValidate="ValidateBoxes" ValidateEmptyText="true"></asp:CustomValidator>
<br />
<br />
<asp:Button ID ="btn" runat="server" Text="Create Event" OnClick="create_Event" />
<asp:Button runat="server" Text="Cancel" OnClick="go_Profile"/>
Output:
This code was tested and works properly.
<body>
<form id="form1" runat="server">
<p>
Please choose what type of Multimedia you would like to upload
</p>
<br />
<asp:TextBox runat="server" PlaceHolder="Photos" ID="pics"></asp:TextBox>
<br />
<asp:TextBox ID="vids" runat="server" PlaceHolder="Videos"></asp:TextBox>
<asp:CustomValidator runat="server" ErrorMessage="Please enter either a photo or a picture!" OnServerValidate="ValidateBoxes" ValidateEmptyText="true"></asp:CustomValidator>
<br />
<br />
<asp:Button ID="btn" runat="server" Text="Create Event" />
<asp:Button runat="server" Text="Cancel" />
</form>
</body>
with this code:
public void ValidateBoxes(object sender, ServerValidateEventArgs e)
{
if (string.IsNullOrEmpty(pics.Text) && string.IsNullOrWhiteSpace(vids.Text))
e.IsValid = false;
else
e.IsValid = true;
}
if I enter any value in either of the two textboxes, the Validator is not shown.
I wanted to leave a comment but figured it would be best to display to you exactly what I tested this way you know what is working.
You have to make sure the Page IsValid before creating your event...
protected void btn_Click(object sender, EventArgs e)
{
if (IsValid)
{
Response.Write("Creating an event");
}
}

Asyncfileupload and button working with updatepanel

I currently having a problem of when I upload a image using asyncfileupload and button inside a updatepanel1, the entire page refresh instead of the image tag in updatepanel2 reload only. How do I make sure that ONLY the image tag in updatepanel2 reload and not the entire page? Do help me out in this problem. THANKS! My markup code is show below.
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" language="javascript">
function StartUpload(sender, args) {
var filename = args.get_fileName();
var path = args.get_path();
if (filename != "") {
// code to get File Extension..
var arr1 = new Array;
arr1 = filename.split("\\");
var len = arr1.length;
var img1 = arr1[len - 1];
var filext = img1.substring(img1.lastIndexOf(".") + 1);
// Checking Extension
if (filext == "jpg" || filext == "JPG") {
$get("<%=lblUpload.ClientID %>").innerHTML = "";
$get("<%=btnUpload.ClientID %>").disabled = false;
return true;
}
else {
$get("<%=lblUpload.ClientID %>").innerHTML = "Only .jpg and .JPG image allowed.";
$get("<%=btnUpload.ClientID %>").setAttribute('disabled', 'disabled');
return false;
}
}
}
</script>
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table width="75%" align="center">
<tr>
<td colspan="5" class="auto-style1">
<h2 align="center">My Profile</h2>
<br />
</td>
</tr>
<tr>
<td id ="memberprofileimage" align="center" class="auto-style2">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Image ID="Image1" runat="server" Height="200" src="image/defaultProfile.jpg" Width="200" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<br />
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red" ThrobberID="Throbber"
UploadingBackColor="#66CCFF"
OnClientUploadStarted="StartUpload"
align="center" />
<br />
<br />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="image/indicator.gif" alt="loading" />
</asp:Label>
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
<br />
<br />
<asp:Label ID="lblUpload" runat="server" Text=""></asp:Label>
</td>
<td id ="memberprofiledetail" align="left" width="50%">
<b> Full Name
<br />
</b>
<asp:TextBox ID="txtFullName" runat="server" ReadOnly="True" Width="270px"></asp:TextBox>
<br />
<b>Contact </b> <br />
<asp:TextBox ID="txtContact" runat="server" ReadOnly="True" Width="160px"></asp:TextBox>
<br />
<b>Address
<br />
</b>
<asp:TextBox ID="txtAddress" runat="server" ReadOnly="true" style="overflow:auto;" TextMode="MultiLine"></asp:TextBox>
<br />
<b>Email
<br />
</b>
<asp:TextBox ID="txtEmail" runat="server" ReadOnly="True" Width="270px"></asp:TextBox>
<br />
<asp:RegularExpressionValidator ID="revContact" runat="server"
ControlToValidate="txtContact"
ValidationExpression="^[0-9]{8}$"
ErrorMessage="Please enter your Contact Number." ForeColor="Red">
</asp:RegularExpressionValidator>
<br />
<asp:RequiredFieldValidator ID="rfvAddress" runat="server"
ErrorMessage="Please enter your Address."
ControlToValidate="txtAddress" ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ErrorMessage="Please enter a valid Email." ForeColor="Red">
</asp:RegularExpressionValidator>
<br />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="BtnDisplay" runat="server" Text="Edit profile" CausesValidation="False" OnClick="BtnDisplay_Click" />
<br />
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Update Profile" OnClick="btnUpdate_Click" Visible="False" />
<br />
<br />
<asp:Button ID="btnChangePassword" runat="server" Text="Change Password" OnClick="btnChangePassword_Click" CausesValidation="False" />
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
Asyncpostbacktrigger don't work with files for security reasons .So full postback is needed in your scenario.
File Upload Issue with UpdatePanel
Here is a great Example of what you need.

Form submits on browser refresh

I am having trouble to find a solution to stop form submission on click of the browser's refresh button.
This is the Login form I have:
<asp:Login ID="EMSLogin" runat="server" OnAuthenticate="EMSLogin_Authenticate">
<LayoutTemplate>
<asp:Panel ID="Panel1" runat="server" CssClass="wrapper">
<asp:Panel ID="Panel2" runat="server" CssClass="holder">
<asp:Panel ID="Panel3" runat="server" CssClass="loginBox one_edge_shadow">
<h1>
Login Credentials</h1>
<asp:Panel ID="Panel4" runat="server" CssClass="name topmargin">
<asp:Panel ID="Panel5" runat="server" CssClass="label">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel6" runat="server" CssClass="textBox">
<telerik:RadTextBox ID="UserName" runat="server" Height="16px" Width="165px" Font-Size="14px"
Font-Names="Arial Sans-Serif" ToolTip="Enter your valid login name" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
ValidationGroup="EMSLogin">*</asp:RequiredFieldValidator>
</asp:Panel>
<br class="clearfix" />
</asp:Panel>
<asp:Panel ID="Panel7" runat="server" CssClass="name topmargin">
<asp:Panel ID="Panel8" runat="server" CssClass="label">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel9" runat="server" CssClass="textBox">
<telerik:RadTextBox ID="Password" runat="server" TextMode="Password" Height="16px"
Width="165px" Font-Size="14px" Font-Names="Arial Sans-Serif" ToolTip="Enter your valid password" />
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
ValidationGroup="EMSLogin">*</asp:RequiredFieldValidator>
</asp:Panel>
<br class="clearfix" />
<telerik:RadButton ID="LoginButton" runat="server" CommandName="Login" Text="Log In"
CssClass="loginButton" Font-Size="14px" Width="100px" ValidationGroup="EMSLogin"
ToolTip="Click to log in" />
</asp:Panel>
</asp:Panel>
</asp:Panel>
</asp:Panel>
</LayoutTemplate>
</asp:Login>
And in the backend:
protected void Page_Load(object sender, EventArgs eventArgs) {
log.Info("=============INSIDE Page_Load======");
DataBind();
LoginErrorWindow.VisibleOnPageLoad = false;
}
protected void EMSLogin_Authenticate(object sender, AuthenticateEventArgs e) {
log.Info("=============INSIDE EMSLogin_Authenticate======");
RadTextBox UserName = EMSLogin.FindControl("UserName") as RadTextBox;
RadTextBox Password = EMSLogin.FindControl("Password") as RadTextBox;
if (Membership.ValidateUser(UserName.Text, Password.Text)) {
FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
} else {
LoginErrorWindow.NavigateUrl = EMSApplication.Web.Utils.NavigationUtils.GetLoginErrorDialogURL();
LoginErrorWindow.VisibleOnPageLoad = true;
}
}
Now after one login failed if I press the refresh button the method EMSLogin_Authenticate is executing again. And before reload it is showing:
How can I solve this?
Do a Response.Redirect to an error page after the login has failed.
See the PRG pattern on Wikipedia.
Post/Redirect/Get (PRG) is a web development design pattern that prevents some duplicate form submissions, creating a more intuitive interface for user agents (users). PRG implements bookmarks and the refresh button in a predictable way that does not create duplicate form submissions.

Jquery pop up window

I'm trying to load a hover page over the current default page. So far the hover pop up window fads in but then in fades out right away. I’m not sure what I’m doing wrong below. Any help would be appreciated.
Js File
var popupStatus = 0;
//loading popup with jQuery magic!
function loadPopup(){
//loads popup only if it is disabled
if(popupStatus==0){
$("#backgroundPopup").css({
"opacity": "0.7"
});
$("#backgroundPopup").fadeIn("slow");
$("#popupContact").fadeIn("slow");
popupStatus = 1;
}
}
//disabling popup with jQuery magic!
function disablePopup(){
//disables popup only if it is enabled
if(popupStatus==1){
$("#backgroundPopup").fadeOut("slow");
$("#popupContact").fadeOut("slow");
popupStatus = 0;
}
}
//centering popup
function centerPopup(){
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popupContact").height();
var popupWidth = $("#popupContact").width();
//centering
$("#popupContact").css({
"position": "absolute",
"top": windowHeight/2-popupHeight/2,
"left": windowWidth/2-popupWidth/2
});
//only need force for IE6
$("#backgroundPopup").css({
"height": windowHeight
});
}
//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){
//LOADING POPUP
//Click the button event!
$("#button").click(function(){
//centering with css
centerPopup();
//load popup
loadPopup();
});
//CLOSING POPUP
//Click the x event!
$("#popupContactClose").click(function(){
disablePopup();
});
//Click out event!
$("#backgroundPopup").click(function(){
disablePopup();
});
//Press Escape event!
$(document).keypress(function(e){
if(e.keyCode==27 && popupStatus==1){
disablePopup();
}
});
});
aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<center>
<img src="Pictures/6.jpg" alt="my image des" />
<div id="button">
<input type="submit" value="Press me please!" /></div>
</center>
<div id="popupContact">
<a id="popupContactClose">x</a>
<p id="contactArea">
Rules:
1) Items with "*" are required fields to be filled out.
<br />
</p>
<asp:Label ID="lblEmail" runat="server" Text="*Your Email: "></asp:Label><asp:TextBox
ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtEmail"
ErrorMessage="You must enter your email address."></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblUserName" runat="server" Text="*Name: "></asp:Label>
<asp:TextBox ID="txtName" runat="server" Width="157px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtName"
ErrorMessage="You must enter a username."></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblCity" runat="server" Text="*City: "></asp:Label>
<asp:TextBox ID="txtCity" runat="server" Width="168px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtCity"
ErrorMessage="You must enter your location."></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblState" runat="server" Text=" State: "></asp:Label>
<asp:TextBox ID="txtState" runat="server" Width="168px"></asp:TextBox><br />
<asp:Label ID="lblAge" runat="server" Text="*Age: "></asp:Label>
<asp:TextBox ID="txtAge" runat="server" Width="165px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtAge"
ErrorMessage="Please enter your age to continue."></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblSex" runat="server" Text="*Gender: "></asp:Label>
<asp:RadioButton ID="rdMale" runat="server" GroupName="Gender" Text="Male" />
<asp:RadioButton ID="rdFemale" runat="server" GroupName="Gender" Text="Female" />
<asp:Label ID="RadialLBL" runat="server"></asp:Label>
<br />
<br />
<asp:Label ID="lblYahoo" runat="server" Text="Yahoo ID: "></asp:Label>
<asp:TextBox ID="YahooID" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblMSN" runat="server" Text="MSN ID: "></asp:Label>
<asp:TextBox ID="MSNID" runat="server" Width="133px"></asp:TextBox>
<br />
<br />
<asp:Label ID="lblMyspaceLink" runat="server" Text="Your Myspace Link: "></asp:Label>
<asp:TextBox ID="MyspaceLink" runat="server" Width="255px"></asp:TextBox>
<br />
<asp:Label ID="lblFaceBookLink" runat="server" Text="Your FaceBook Link: "></asp:Label>
<asp:TextBox ID="FaceBooklink" runat="server" Width="244px"></asp:TextBox>
<br />
<asp:Label ID="lblUploadpic" runat="server" Text="*Upload your picture."></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" Height="22px" Width="217px" /><br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label><br />
<br />
<asp:Label ID="lblDesctiption" runat="server" Text="*User Bio: "></asp:Label><br />
<asp:TextBox ID="txtDescription" runat="server" MaxLength="240" Width="390px" Height="73px"
Rows="3" TextMode="MultiLine"></asp:TextBox><br />
<br />
<asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txtDescription"
ErrorMessage="Enter a bio or description of yourself."></asp:RequiredFieldValidator>
<br />
<asp:Label ID="EnterAll" runat="server"></asp:Label>
<asp:Label ID="Displayme" runat="server" Text=""></asp:Label>
<br />
<br />
</div>
<div id="backgroundPopup">
</div>
A good first step is to ensure that your click events are being properly handled to prevent unwanted bubbling. You can do this with each of the click handling functions:
$("#button").click(function(e){
e.preventDefault();
//centering with css
centerPopup();
//load popup
loadPopup();
});
That may cause the problem to stop happening, and even if it doesn't, it's a good idea to prevent weird behavior from happening in the future. You can read more about preventDefault here: http://api.jquery.com/event.preventDefault/

Formview: check if record exist when user try to insert data ASP.NET C#

Is there a way were I could generate a message box if a record exist in the database after the user clicked the insert link button? I want the formview to check if record exist if not make an insert.
Help would be much appreciated.
Thanks in advance :)
Here's a sample of my code:
Manage Books
Add/Remove Books
Note: For the book ID/ISBN please refer to the barcode in the ISBN, usually located
at the back of the book. A barcode reader is required.
<EditItemTemplate>
Book ID/ISBN:
<asp:Label ID="bookidLabel1" runat="server" Text='<%# Eval("bookid") %>' />
<br />
Title:
<asp:TextBox ID="booktitleTextBox" runat="server"
Text='<%# Bind("booktitle") %>' />
<br />
Author's lastname:
<asp:TextBox ID="lastnameTextBox" runat="server"
Text='<%# Bind("lastname") %>' />
<br />
Author's firstname:
<asp:TextBox ID="firstnameTextBox" runat="server"
Text='<%# Bind("firstname") %>' />
<br />
Description:
<asp:TextBox ID="descriptionTextBox" runat="server"
Text='<%# Bind("description") %>' />
<br />
Category:
<asp:TextBox ID="categoryidTextBox" runat="server"
Text='<%# Bind("categoryid") %>' />
<br />
Date added:
<asp:TextBox ID="dateaddedTextBox" runat="server"
Text='<%# Bind("dateadded") %>' />
<br />
Status:
<asp:TextBox ID="statusidTextBox" runat="server"
Text='<%# Bind("statusid") %>' />
<br />
Quantity:
<asp:TextBox ID="quantityTextBox" runat="server"
Text='<%# Bind("quantity") %>' />
<br />
name:
<asp:TextBox ID="nameTextBox" runat="server" Text='<%# Bind("name") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<InsertItemTemplate>
Book ID:
<asp:TextBox ID="bookidTextBox" runat="server" Text='<%# Bind("bookid") %>' />
<asp:RequiredFieldValidator ID="RequesFieldValidator1" runat="server" ErrorMessage="* Required" ControlToValidate="bookidTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator" runat="server" Display="Dynamic" ControlToValidate="bookidTextBox" ValidationExpression="^([\S\s]{13,13})$" ErrorMessage="Invalid ID/ISBN. Please try again" ValidationGroup="InsertBook">
</asp:RegularExpressionValidator>
<br />
Title:
<asp:TextBox ID="booktitleTextBox" runat="server"
Text='<%# Bind("booktitle") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="* Required" ControlToValidate="booktitleTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Author's lastname:
<asp:TextBox ID="lastnameTextBox" runat="server"
Text='<%# Bind("lastname") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="* Required" ControlToValidate="lastnameTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Author's firstname:
<asp:TextBox ID="firstnameTextBox" runat="server"
Text='<%# Bind("firstname") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="* Required" ControlToValidate="firstnameTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Description:
<asp:TextBox ID="descriptionTextBox" runat="server"
Text='<%# Bind("description") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="* Required" ControlToValidate="descriptionTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Category:
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="categoryDataSource" DataTextField="name"
DataValueField="categoryid" SelectedValue='<%# Bind("categoryid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="categoryDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [categoryid], [name] FROM [TblCategory]">
</asp:SqlDataSource>
<br />
Date added:
<asp:TextBox ID="dateaddedTextBox" runat="server"
Text='<%# Bind("dateadded") %>'/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="* Required" ControlToValidate="dateaddedTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<%--<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="dateaddedTextBox" ErrorMessage="RegularExpressionValidator"
ValidationExpression="(19|20)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])">
</asp:RegularExpressionValidator>--%>
<br />
Status:
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="statusDataSource" DataTextField="statusname"
DataValueField="statusid" SelectedValue='<%# Bind("statusid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="statusDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [statusid], [statusname] FROM [BookStatus]">
</asp:SqlDataSource>
<br />
Quantity:
<asp:TextBox ID="quantityTextBox" runat="server"
Text='<%# Bind("quantity") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ErrorMessage="* Required" ControlToValidate="quantityTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Add" ValidationGroup="InsertBook"/>
<asp:Button ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</ItemTemplate>
<EmptyDataTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</EmptyDataTemplate>
<HeaderTemplate>
Add a new book
</HeaderTemplate>
</asp:FormView>
You can check in the ItemInserting method.
Something like:
void FormViewName_ItemInserting(object sender, FormViewInsertEventArgs e)
{
string somevalue = e.Values["somefieldtoget"];
//make your calls to the DB to check the somevalue doesn't exist
if(exists)
e.Cancel = true;
}
You can also do this on the data sources Inserting Method (sql datasource assumed) as well....
void datasourcename_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
...
}
Another approach as mentioned by #steve-wellens is if you have a primary key that is based on one or more of the fields in the form view (not an auto generated number then below will work great for catching an attempt to insert a duplicate key/record.
void FormViewName_ItemInserted(object sender, FormViewInsertedEventArgs e)
{
if (e.Exception != null)
{
if (((SqlException)e.Exception).Number == 2627)
{
e.ExceptionHandled = true;
e.KeepInInsertMode = true;
// Display error message.
}
}
}
It would be better to put a unique index on the table and catch exceptions that occur when an attempt is made to insert a duplicate record.
It's the simplest way to ensure integrity. Otherwise you have to start a read transaction to handle the case where between the time you check and the time you insert, some other process is doing the exact same thing.

Categories