I'm working in asp.net with c# and I decided to build a pop-up messaging module. I have done this on previous projects; however, I've never used it on a site that was also utilizing the Identity Framework or placed in my master page. I am also fairly new to C#.
The messenger appears to be working fine. However, now any kind of "submit" or "send" function found on the master page will not work properly. For example, if I try to log in as an admin, I will get my windows error messages for the field validation on the messenger. I tried taking out the RequiredFieldValidators, I was still unable to log in, instead it tried to send a message.
I then tried moving the module into a usercontrol and running it that way, still no luck. I had considered building a new masterpage for the log in page, that way I could remove the "contact" from the navigation on that page, thus eliminating the issue . However, I would prefer not to have to do this. I am sure there is a simple solution to correcting this, and my lack of experience with c# is not helping much.
Here is part of the navigation on my Site.Master, just to give an idea about what I'm doing:
<li><a runat="server" href="#" data-toggle="modal" data-target=".pop-up-1">Contact</a></li>
</ul>
<asp:LoginView runat="server" ViewStateMode="Disabled">
<AnonymousTemplate>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/Account/Login" style="color:#f46de6">Admin</a></li>
<li><asp:HyperLink ID="PayPalViewCart" runat="server" NavigateUrl=<%# Link.ToPayPalViewCart() %> style="color:#f46de6">View Cart</asp:HyperLink></li>
</ul>
</AnonymousTemplate>
<LoggedInTemplate>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/Account/Manage" title="Manage your account" style="color:#f46de6" >Hello, Admin</a></li>
<li>
<asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Log off" LogoutPageUrl="~/" OnLoggingOut="Unnamed_LoggingOut" />
</li>
</ul>
</LoggedInTemplate>
</asp:LoginView>
</div>
</div>
</div>
<uc1:popup1 runat="server" id="popup1" />
<div class="container body-content">
Now here is the code behind on this page, site.Master.cs:
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
}
else
{
// Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
{
Context.GetOwinContext().Authentication.SignOut();
}
}
}
This is my user control for the pop-up:
<div class="modal fade pop-up-1" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel-1" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myLargeModalLabel-3">Contact Us</h4>
</div>
<div class="modal-body">
<table style="max-width:100%; height: auto; padding:20px">
<tr>
<td colspan="3">
<div style="margin:15px 0 20px 0"> Please, use the form below to contact us regarding any questions or concerns you might have:</div>
</td>
</tr>
<tr style="margin-bottom:10px">
<td style="width:150px; font-size:14px">Name:</td>
<td style="vertical-align:top; width:300px">
<asp:TextBox ID="txtName" runat="server" Width="300px" style="margin:10px"/>
</td>
<td>
<!--<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName" Display="Dynamic"
ErrorMessage="Name">*</asp:RequiredFieldValidator>-->
</td>
</tr>
<tr style="margin-bottom: 10px ">
<td style="font-size: 14px">Organization (optional):</td>
<td><asp:TextBox ID="txtOrganization" runat="server" Width="300px" style="margin:10px" /></td>
<td>
</td>
</tr>
<tr style="margin-bottom:10px">
<td style="font-size:14px"> Phone (optional):</td>
<td><asp:TextBox ID="txtPhone" runat="server" Width="300px" style="margin:10px" /></td>
<td>
</td>
</tr>
<tr style="margin-bottom:10px">
<td style="font-size:14px">Email:</td>
<td><asp:TextBox ID="txtEmail" runat="server" Width="300px" style="margin:10px" /></td>
<td>
<!--<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
ControlToValidate="txtEmail" Display="Dynamic"
ErrorMessage="Email">*</asp:RequiredFieldValidator>-->
</td>
</tr>
<tr>
<td style="font-size:14px"> Message:</td>
<td><asp:TextBox ID="txtRequest" runat="server" TextMode="MultiLine" Width="300px" Height="60px" style="margin:10px" /></td>
<td>
<!--<asp:RequiredFieldValidator ID="rfvRequest" runat="server"
ControlToValidate="txtRequest" Display="Dynamic"
ErrorMessage="Message">*</asp:RequiredFieldValidator>-->
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SendMail" Width="60px" />
<asp:Button ID="btnReset" runat="server" Text="Reset" OnClick="ResetEmail" Width="60px" CausesValidation="false" />
<!--<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Please fill out the required fields:" ShowMessageBox="true" ShowSummary="false" />-->
</td>
</tr>
</table>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal Contact Table-->
And last but not least, this is the code behind on the user control, and yes I know I can do this using my web.config also, and I tried that too with the same result:
public partial class pop_up_1 : System.Web.UI.UserControl
{
private bool IsValid;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SendMail(object sender, EventArgs e)
{
if (IsValid)
{
//create a new email message
MailMessage mail = new MailMessage();
mail.From = new MailAddress("");
mail.To.Add("");
mail.Subject = "Information Request";
mail.IsBodyHtml = true;
mail.Body = "Name:" + this.txtName.Text + "<br />";
mail.Body += "Organization:" + txtOrganization.Text + "<br />";
mail.Body += "Phone:" + txtPhone.Text + "<br />";
mail.Body += "Email:" + txtEmail.Text + "<br />";
mail.Body += "Request or Question:" + txtRequest.Text + "<br />";
//Create SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "";
//Send the email
smtp.Send(mail);
//Define the name and type of the client script on the page.
String csName = "SuccessNotificationScript";
Type csType = this.GetType();
//Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
//Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
string csText = "<script language='javascript'>window.alert('Thank you for submitting your request');</script>";
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
//Clear the form
ClearForm();
}
}
protected void ResetEmail(object sender, EventArgs e)
{
ClearForm();
}
protected void ClearForm()
{
txtName.Text = "";
txtOrganization.Text = "";
txtPhone.Text = "";
txtEmail.Text = "";
txtRequest.Text = "";
}
}
}
Any suggestions or ideas, greatly appreciated. Thanks
here is the backend of my login page, I am using identity framework:
public partial class Login : Page
{
protected void Page_Load(object sender, EventArgs e)
{
//RegisterHyperLink.NavigateUrl = "Register";
// Enable this once you have account confirmation enabled for password reset functionality
// ForgotPasswordHyperLink.NavigateUrl = "Forgot";
//OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
if (!String.IsNullOrEmpty(returnUrl))
{
//RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
}
}
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = manager.Find(Email.Text, Password.Text);
if (user != null)
{
IdentityHelper.SignIn(manager, user, RememberMe.Checked);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
FailureText.Text = "Invalid username or password.";
ErrorMessage.Visible = true;
}
}
}
}
}
Related
I've been looking for this answer for a couple weeks now but many other questions/answers don't fit my project or simply don't work.
Let me explain my project.
It is a simple View Page which on page load it would set the Text to different fields throughout the page. On the bottom I have a container with buttons which control which div is displayed in the container. On each click of the button, I run some code to set data sources to grid views or fill fields with text. I noticed when I click F5 to refresh the page I get that pesky "form resubmission" popup which will cause the last button click such as appending a note to a listview to be duplicated.
Here is some code to understand what I am doing
HTML(Not complete, just necessary to understand my question)
<td style="vertical-align: top;" class="Flow-Sub-Menu">
<asp:Button ID="Button_Sub_Menu_Financial" runat="server" Text="Financial Info" OnClick="Button_Sub_Menu_Financial_Click" />
<asp:Button ID="Button_Sub_Menu_Indemnitors" runat="server" Text="Indemnitors" OnClick="Button_Sub_Menu_Indemnitors_Click" />
<asp:Button ID="Button_Sub_Menu_Court" runat="server" Text="Court Info" OnClick="Button_Sub_Menu_Court_Click" />
<asp:Button ID="Button_Sub_Menu_Forfeiture" runat="server" Text="Forfeiture Info" OnClick="Button_Sub_Menu_Forfeiture_Click" />
<asp:Button ID="Button_Sub_Menu_Collaterals" runat="server" Text="Collaterals" OnClick="Button_Sub_Menu_Collaterals_Click" />
<asp:Button ID="Button_Sub_Menu_Notes" runat="server" Text="Notes" OnClick="Button_Sub_Menu_Notes_Click" />
<asp:Button ID="Button_Sub_Menu_Documents" runat="server" Text="Documents" OnClick="Button_Sub_Menu_Documents_Click" />
</td>
<div id="Div_Sub_Menu_Notes" runat="server" visible="false">
<div class="row">
<div class="col-xs-4" style="min-width: 550px;">
<div class="Flow-Box">
<div class="Flow-Box-Content" style="height: 440px; overflow-y: scroll;">
<asp:ListView ID="LV_Notes" runat="server" ItemPlaceholderID="ItemPlaceHolder" DataKeyNames="Bond_Note_ID" OnPagePropertiesChanging="LV_Notes_PagePropertiesChanging" OnItemCommand="LV_Notes_ItemCommand">
<LayoutTemplate>
<table style="width: 500px; background-color: white;">
<tr id="ItemPlaceHolder" runat="server"></tr>
<tr>
<td colspan="2">
<asp:DataPager ID="DataPager_Notes" runat="server" PagedControlID="LV_Notes" PageSize="3">
<Fields>
<asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true"
ShowNextPageButton="false" />
<asp:NumericPagerField ButtonType="Link" />
<asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td colspan="2" style="padding-left: 10px; padding-right: 10px;">
<div style="border: 2px solid grey; height: 75px; padding: 5px;">
<%# Eval("Note") %>
</div>
</td>
</tr>
<tr>
<td style="padding-left: 10px;" <%# (Eval("Document_ID").ToString() != "" ? "" : "hidden=\"hidden\"") %>>
<label>Document Attached : <%# Eval("Document_Title").ToString() %></label>
</td>
<td style="text-align: right; padding-right: 10px;" <%# (Eval("Document_ID").ToString() != "" ? "" : "hidden=\"hidden\"") %>>
<asp:Button ID="Button_View_Document" runat="server" Text="View/Download Document" CommandName="View_Document" CommandArgument='<%#Eval("Document_ID")%>' />
</td>
</tr>
<tr>
<td style="text-align: left; padding-left: 10px;">
<div>
<%# Convert.ToDateTime(Eval("Created_DateTime")).ToShortDateString() + " " + Convert.ToDateTime(Eval("Created_DateTime")).ToShortTimeString() %>
</div>
</td>
<td style="text-align: right; padding-right: 10px;">
<div>
<%# Eval("Full_Name") %>
</div>
</td>
</tr>
<tr>
<td colspan="2" style="height: 20px; border-top: 4px solid #009900;"></td>
</tr>
</ItemTemplate>
</asp:ListView>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-4" style="min-width: 500px;">
<div class="Flow-Box">
<div class="Flow-Box-Label">
New Note
</div>
<div class="Flow-Box-Content">
<table class="Flow-Box-Table">
<tr>
<td>
<textarea id="TextArea_New_Note" runat="server" style="width: 400px; height: 150px;"></textarea>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button_Append_New_Note" runat="server" OnClick="Button_Append_New_Note_Click" Text="Append Note" />
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
C# Codebehind
protected void Button_Sub_Menu_Notes_Click(object sender, EventArgs e)
{
resetSubMenuButtons();
Button_Sub_Menu_Notes.BackColor = System.Drawing.Color.Orange;
Div_Sub_Menu_Notes.Visible = true;
string bondID = Request.QueryString["BondID"];
bindNotes(bondID);
}
protected void bindNotes(string bondID)
{
DataTable dt = Common_Functions.GetData("SELECT * FROM View_Bond_Notes_With_Name WHERE Bond_ID='" + bondID + "' ORDER BY Created_DateTime DESC");
LV_Notes.DataSource = dt;
LV_Notes.DataBind();
}
protected void LV_Notes_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
(LV_Notes.FindControl("DataPager_Notes") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
string bondID = Request.QueryString["BondID"];
bindNotes(bondID);
}
protected void LV_Notes_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (String.Equals(e.CommandName, "View_Document"))
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
string documentID = e.CommandArgument.ToString();
Session["BondDocumentID"] = documentID;
Page.ClientScript.RegisterStartupScript(GetType(), "openDocument", "window.open('/FileServing/Bond_Document_Server.aspx');", true);
}
}
protected void Button_Append_New_Note_Click(object sender, EventArgs e)
{
string bondID = Request.QueryString["BondID"];
string UserID = Request.Cookies["UserID"].Value;
string newNote = TextArea_New_Note.Value;
if (String.IsNullOrWhiteSpace(newNote))
{
return;
}
cmd = new SqlCommand("INSERT INTO Bond_Notes " +
"(Bond_ID, Created_DateTime, Created_By, Note) " +
"VALUES " +
"(#Bond_ID, #Created_DateTime, #Created_By, #Note)", conn);
cmd.Parameters.AddWithValue("#Bond_ID", bondID);
cmd.Parameters.AddWithValue("#Created_DateTime", DateTime.Now);
cmd.Parameters.AddWithValue("#Created_By", UserID);
cmd.Parameters.AddWithValue("#Note", (String.IsNullOrWhiteSpace(newNote) ? (object)DBNull.Value : newNote));
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
TextArea_New_Note.Value = "";
bindNotes(bondID);
}
So when the user clicks "Button_Append_New_Note", the code will fire to run the sqlcommand and then refreshes the ListView by calling the "bindNotes(bondID)". If the user clicks F5 or hits refresh for whatever reason, they are resubmitting that form and add duplicates. I've read many solutions to redirect to the same page, this will not work in my case since the div would be hidden again and I would prefer the Notes div to stay visible so the user can see their new note in the listview. I also prefer not to have an sql check to look for a duplicate and prevent an insert since I may want the user to insert duplicates if they chose to at another time, but the user would manually type in the duplicate.
Any recommendations or suggestions on how to avoid the form resubmission?
Also please no criticizing on the code, I am looking for answers, not a lecture on why its bad to build an SQL sentence with inline string addition. I will correct and optimize these faults eventually.
If you found my solution elsewhere, please ensure it would work in my case cause I have found my same question many times, but not with my scenario.
Thanks in advance.
As you probably know, ASP.NET Web Forms send POST requests back to the server and then re-render the Page in the same request. This is why we see the form re-submission message when we click "reload".
To avoid this issue, we should employ the post-then-redirect pattern used by many web applications. Here's a quick overview:
A user clicks a button which submits the form as a POST request.
The server receives the request and saves the data.
The server issues a redirect response along with any needed state.
The browser receives the redirect and loads the appropriate page by sending a GET request.
Because we redirect the browser to a new (or the same) location, this clears the POST data from the previous request so we can hit "reload" without re-submitting the same data again. The URL that we redirect to should contain only the data needed for the server to interpret what to display on the page. This pattern provides a durable way to maintain state between requests in HTTP.
To apply this to the Web Form in the question, we need to change some assumptions about how the page loads. Instead of binding the notes to the page after running each POST action, we'll redirect the user first, and then bind the notes:
protected void Button_Append_New_Note_Click(object sender, EventArgs e)
{
string bondID = Request.QueryString["BondID"];
// Save the new note...
Response.Redirect("http://example.com/Page.aspx?BondID=" + bondID);
}
Then, when the browser loads the redirect:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindNotes(Request.QueryString["BondID"]);
}
}
We'll need to change each of the post-back methods to use this pattern. Some of the methods may need to add additional parameters to the redirect URL that the page reads to configure the display.
This is quite easy and blocks the pop up asking for form resubmission on refresh once the form is submitted. Just place this line of javascript code at the footer of your file and see the magic.
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
I have looked at a number of solutions to my basic issue, but have not found any solution that I either understand or that would work.
I have a page that takes in two items of information, filename and a store. The user then clicks on a button to execute a function that will update a database and send back a resulting string that I want to display on a textbox on the main form.
However, when they press the button I call a modalpopupextender using an UpdatePanel panel. That gets a value into the modalpopup. If the user validates that the correct store is selected they click an 'okay' button which then call the dbprocessing function that returns a result. The page is small so I'll give the complete aspx and c# code.
The function doProcess() returns a List of values which I convert to String for display. I left the session variables in for that was my last attempt at trying to get this to work.
Where I am confused is that when the first button on the main form (Process) is clicked, there is a postback which obviously hits the page load before the button click. That is when I display the popup. Then when the user clicks on the button Okay, another postback is perform hitting page load before the button click and in that second button I originally tried to set the textbox on the main page because there is no other action after the second click, but no data displayed.
What is strange, if I repeat the process, when I click to display the popup, my data displays. This is not making sense.
This is the aspx page
<%# Page Title="Product Rank Loader" Language="C#" MasterPageFile="~/OMnested.master" AutoEventWireup="true" CodeBehind="ProductRankLoader.aspx.cs" Inherits="OrderManager.ProductRankLoader" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="Scripts/local.js"></script>
<script type="text/javascript">
function callme(thisone)
{
$("#ddlStores").prop('disabled', false);
}
</script>
<div>
<table style="width: 500px">
<tr>
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:FileUpload ID="fulRanks" runat="server" Width="315px" />
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlStores" runat="server" Height="16px" Width="155px">
<asp:ListItem Value="0">Select Store</asp:ListItem>
<asp:ListItem Value="10101">Parkseed</asp:ListItem>
<asp:ListItem Value="10151">Wayside</asp:ListItem>
<asp:ListItem Value="10201">Jackson (JP)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td style="height: 20px; padding-top: 15px; padding-bottom: 15px; padding-left: 20px;">
<asp:Button ID="btnProcess" runat="server" Text="Process" Width="89px" OnClick="btnProcess_Click" />
</td>
</tr>
<tr>
<td>
**<asp:TextBox ID="txtResults" runat="server" Height="200px" ReadOnly="True" TextMode="MultiLine"></asp:TextBox>**
</td>
</tr>
</table>
<asp:HiddenField ID="hdnFilename" runat="server" />
</div>
<asp:UpdatePanel id="updVerifyChoice" runat="server">
<ContentTemplate>
<div style="display: none;">
<asp:Button ID="btnDummy" UseSubmitBehavior="true" OnClientClick="ShowModalPopup" OnClick="btnDummy_Click" runat="server" />
<%--Dummy Button added to assign the target controlid of PopupExtender--%>
<asp:Button ID="btnDummyButton" UseSubmitBehavior="true" runat="server" Text="DummyButton" Style="display: none;" />
</div>
<asp:Panel ID="pnlVerifyRequestPopup" runat="server">
<div style="background: #fff; padding-left: 3px; border: 1px solid #989898; border-top: 1px solid #989898 !important;">
<table style="background-color: #F7F5F4; width: 300px;">
<tr>
<td><label>Verify Process Request</label></td>
<td style="text-align: right;">
<label class="lbl_3">
<asp:LinkButton ID="lBtnVerifyRequestClose" CssClass="lnkCloseheaderedit" Text="Cancel"
runat="server" OnClick="lBtnBillUpdPopClose_Click" /></label>
</td>
</tr>
<tr>
<td style="width: 150px;" colspan="2">
<asp:Label ID="lblWarn" runat="server" Text="" Font-Size="Medium" ForeColor="#CC3300"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" class="align_right">
<asp:Button ID="btnPopVerify" runat="server" CssClass="order_searchbtn" Text="Okay"
OnClick="btnPopVerify_Click" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnReturnData" runat="server" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender ID="extVerifyProcess" runat="server" BehaviorID="extndPopBillUpdBehId"
TargetControlID="btnDummyButton" PopupControlID="pnlVerifyRequestPopup" CancelControlID="lBtnVerifyRequestClose">
</ajax:ModalPopupExtender>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The field in question that should get the returned values from the function is called txtResults.
Here is the c# code (I cut out unneeded code)
namespace OrderManager
{
public partial class ProductRankLoader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var currentUser = Request.LogonUserIdentity.Name.Split('\\')[1];
// Session.Add("returnText", "");
var header = Master.FindControl("lblpageheading") as Label;
header.Text = "Product Rank Loader";
if (IsPostBack)
{
try
{
//if (Session["Verified"].ToString() != "")
//{
Session["returnText"] = doProcess();
if (Session["returnText"].ToString() != "")
{
txtResults.Text = Session["returnText"].ToString();
lblMessage.Text = "";
}
//}
}
catch { }
} else
{
Session.Add("returnText", "");
Session.Add("Verified", "");
}
}
protected void btnProcess_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
string filename = Path.GetFileName(fulRanks.FileName);
hdnFilename.Value = filename;
if (fulRanks.HasFile)
{
ddlStores.Enabled = true;
String fileExtension =
System.IO.Path.GetExtension(fulRanks.FileName).ToLower();
String[] allowedExtensions = { ".txt", ".log" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
fulRanks.SaveAs(#"c:\temp\" + filename);
}
}
}
if (!fileOK || ddlStores.SelectedIndex <= 0)
{
lblMessage.Text = "Either the file name is incorrect or a store has not been selected.";
return;
} else { }
lblWarn.Text = "You are going to update item Ranks for store <br />" + ddlStores.SelectedItem + ".<br /><br />Press 'Okay' to process";
Session.Add("Verified", "true");
extVerifyProcess.Show();
}
protected void lBtnBillUpdPopClose_Click(object sender, EventArgs e)
{
Session["Verified"] = "";
Session["returnText"] = "";
Response.Redirect("ProductRankLoader.aspx");
}
protected void btnPopVerify_Click(object sender, EventArgs e)
{
//Session["returnText"] = doProcess();
Session.Remove("returnText");
Session.Remove("Verified");
}
private string doProcess()
{
string tmpResults = "";
Int32 store = 0;
if (ddlStores.SelectedIndex > 0)
{
Int32.TryParse(ddlStores.SelectedValue.ToString(), out store);
string filename = hdnFilename.Value;
ProductRankLoaderDLL.ProductRankLoaderDLL newRanks = new ProductRankLoaderDLL.ProductRankLoaderDLL(xxx);
List<string> results = newRanks.ProcessRanks();
foreach (string result in results)
{
tmpResults += result + '\r';
}
// txtResults.Text = tmpResults;
lblMessage.Text = "";
}
else
{
lblMessage.Text = "";
}
return tmpResults;
}
protected void btnDummy_Click(object sender, EventArgs e)
{
}
}
}
If I don't misunderstand your request your problem is caused by the postbacks. I think you can handle better your logic with jquery. For example you can use jquery to close the popup without performing postback:
$('#lBtnVerifyRequestClose').click(function (event) {
event.preventDefault();
$('#pnlVerifyRequestPopup').dialog('close');
});
the event.preventDefault() ensure that postback are not executed.
If you need server logic to put data on your popup you can bind a jquery function to the dialog on open event and retrieve there data / perform your logic. In this way your form will be submitted to the server only once at the end of the process.
I would like to take all information stored in a repeater and place it in the body of an email message for sending. Basically, it's a product order form (which also makes use of a repeater) that sends users to an order review page with a form at the bottom that allows them to send the order information to someone else. I am allowed to set up the order information as a table. I have everything working, and my code successfully sends emails. However, I am not sure how to pull the order review repeater's contents into the message body for an email.
Any suggestions/tips are appreciated! Thanks!
Designer code:
<asp:Repeater ID="orderRepeater" runat="server" >
<itemtemplate>
<%# Eval("LocationName") %>
<div class="headerRow">
<div class="header">
<div class="thumb">
<p></p>
</div>
<div class="headerField name"><p class="hField">Product</p></div>
<div class="headerField sku"><p class="hField">GOJO SKU</p></div>
<div class="headerField size"><p class="hField">Size</p></div>
<div class="headerField case"><p class="hField">Case Pack</p></div>
<div class="headerField qty"><p class="hField">Quantity</p></div>
</div>
</div>
<div class="table">
<div class="row">
<div class="thumb"><%# Eval("Thumbnail") %></div>
<div class="field name"><p class="pField"> <%#Eval("ProductName") %> </p></div>
<div class="field sku"><p class="pField"> <%#Eval("Sku") %></p></div>
<div class="field size"><p class="pField"> <%#Eval("Size") %></p></div>
<div class="field case"><p class="pField"><%#Eval("CasePack") %></p></div>
<div class="field qty"><p class="pField"><%#Eval("Qty") %></p></div>
</div>
</div>
</itemtemplate>
</asp:Repeater>
<asp:placeholder id="form" runat="server">
<asp:label id="msgLbl" runat="server" text=""></asp:label>
<asp:hyperlink id="link" runat="server" visible="false" NavigateUrl="/united-states/market/office-buildings/obproductmap/ProductList" >Product Listing</asp:hyperlink><br />
<asp:hiddenfield id="emailTbl" runat="server"></asp:hiddenfield>
<div id="emailForm">
<asp:ValidationSummary ID="vsEmailForm" runat="server" ForeColor="red" DisplayMode="BulletList" /><br />
<div id="yourFields">
<div id="yNameInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvYName" ForeColor="red"
ControlToValidate="yName" errormessage="You must enter your name" Text="*"
Display="Dynamic" SetFocusOnError="True"></asp:requiredfieldvalidator>
Your Name:<br /> <asp:TextBox runat="server" id="yName" size="40"></asp:TextBox>
</div>
<div id="yEmailInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvYEmail" ForeColor="red"
ControlToValidate="yEmail" Display="Dynamic"
errormessage="You must enter your email" Text="*" SetFocusOnError="True"></asp:requiredfieldvalidator>
<asp:regularexpressionvalidator runat="server" id="revYEmail" ForeColor="red"
ControlToValidate="yEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
errormessage="Your email address is not valid. Please try again." Text="*"
Display="Dynamic" SetFocusOnError="True"></asp:regularexpressionvalidator>
Your Email: <br /> <asp:TextBox runat="server" id="yEmail" size="40"></asp:TextBox><br /><br />
</div>
</div>
<div id="reFields">
<div id="rNameInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvRName" ForeColor="red"
ControlToValidate="rName" Text="*"
errormessage="You must enter a recipient's name" Display="Dynamic"
SetFocusOnError="True"></asp:requiredfieldvalidator>
Recipient's Name: <br /><asp:TextBox runat="server" id="rName" size="40"></asp:TextBox>
</div>
<div id="rEmailInfo" class="fieldBlock">
<asp:requiredfieldvalidator runat="server" id="rfvREmail" ForeColor="red"
ControlToValidate="rEmail" Display="Dynamic" Text="*"
errormessage="You must enter a recipient's email" SetFocusOnError="True"></asp:requiredfieldvalidator>
<asp:regularexpressionvalidator runat="server" id="revREmail" ForeColor="red"
ControlToValidate="rEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
errormessage="The recipient's email address is not valid. Please try again."
Text="*" Display="Dynamic" SetFocusOnError="True"></asp:regularexpressionvalidator>
Recipient's Email:<br /> <asp:TextBox runat="server" id="rEmail" size="40"></asp:TextBox><br /><br />
</div>
</div>
<div id="buttons">
<asp:Button id="submit" Text="Submit" runat="server" CausesValidation="true"
onclick="submitBtn" />
<asp:Button id="cancel" Text="Cancel" runat="server" CausesValidation="false" /><br /><br />
<asp:Button id="print" Text="Print" runat="server" CausesValidation="false "/>
<asp:Button id="pdf" Text="Save as PDF" runat="server" CausesValidation="false" />
</div>
</div>
</asp:placeholder>
<asp:placeholder id="sentMsg" visible="false" runat="server">
<asp:Label id="lbl" runat="server" Text="Your message has been sent!"></asp:Label>
</asp:placeholder>
Code behind:
protected void getOrder(Item CurrentItem)
{
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (Session["orderComplete"] != null && Session["orderComplete"] != "")
{
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoOrderReview']");
Database db = Sitecore.Context.Database;
DataSet dset = new DataSet();
if (ProductGroup != null)
{
string InFromSession = Session["orderComplete"].ToString();
try
{
DataTable summary = dset.Tables.Add("summary");
summary.Columns.Add("LocationName", Type.GetType("System.String"));
summary.Columns.Add("Thumbnail", Type.GetType("System.String"));
summary.Columns.Add("ProductName", Type.GetType("System.String"));
summary.Columns.Add("Sku", Type.GetType("System.String"));
summary.Columns.Add("Size", Type.GetType("System.String"));
summary.Columns.Add("CasePack", Type.GetType("System.String"));
summary.Columns.Add("Qty", Type.GetType("System.String"));
summary.Columns.Add("Location", Type.GetType("System.String"));
Label qL = (Label)FindControl("qty");
string[] orders = InFromSession.Split(';');
string tempheader = "";
foreach (string order in orders)
{
DataRow drow = summary.NewRow();
if (order != "")
{
string[] things = order.Split(',');
string skus = things.GetValue(0).ToString();
if (skus != "")
{
Item locName = db.Items[skus];
Item LocationItem = ScHelper.FindAncestor(locName, "gojoProductLocation");
if (LocationItem != null)
{
string LocationName = LocationItem.Fields["Header"].ToString();
if (tempheader != LocationName)
{
drow["LocationName"] = "<div><h1>" + LocationName + "</h1></div>";
tempheader = LocationName;
}
}
}
}
string purchase = order;
int total = orders.GetUpperBound(0);
if (purchase != "")
{
string[] infos = purchase.Split(',');
string ids = infos.GetValue(0).ToString();
string qtys = infos.GetValue(1).ToString();
if (ids != "")
{
Item anItem = db.Items[ids];
Item orderItem = db.Items[anItem.Fields["Reference SKU"].Value];
if (orderItem != null)
{
Item marketItem = db.Items[orderItem.Fields["Master Product"].Value];
if (marketItem != null)
{
Item CPNItem = db.Items[marketItem.Fields["Complete Product Name"].Value];
drow["Thumbnail"] = "";
Sitecore.Data.Fields.XmlField fileField = marketItem.Fields["Thumbnail"];
drow["Thumbnail"] = "<image src=\"" + ScHelper.GetCorrectFilePath(fileField) + "\" border=\"0\" alt=\"\">";
if (CPNItem != null)
{
var name = CPNItem["Complete Name"];
drow["ProductName"] = name;
}
drow["Sku"] = marketItem.Fields["SKU"].Value;
drow["CasePack"] = marketItem.Fields["Case Pack"].Value;
if (marketItem.Fields["Size"] != null)
{
drow["Size"] = marketItem.Fields["Size"].Value;
}
else
{
drow["Size"] = "N/A";
}
drow["Qty"] = qtys.ToString();
summary.Rows.Add(drow);
}
}
}
}
}
orderRepeater.DataSource = dset;
orderRepeater.DataMember = "summary";
orderRepeater.DataBind();
}
catch (Exception x)
{
//
}
}
}
}
else
{
HyperLink none = (HyperLink)FindControl("link");
Label msg = (Label)FindControl("msgLbl");
none.Visible = true;
msg.Text = "You have not selected any items for purchase. To purchase items, please visit our complete product listing: ";
}
}
protected void sendEmail()
{
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoOrderReview");
if (HomeItem != null)
{
TextBox rTxt = (TextBox)FindControl("rEmail");
TextBox fName = (TextBox)FindControl("yName");
try
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.To.Add(rTxt.Text);
msg.Subject = "GOJO product order summary";
msg.From = new System.Net.Mail.MailAddress("donotreply#GOJO.com");
msg.Body = "Here is a list of the products your friend, " + fName.Text + ", has selected: ";
msg.IsBodyHtml = true;
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient("mail.innismaggiore.com");
sc.Send(msg);
}
catch (Exception EX)
{
GOJOHelper.WriteLog("GOJO Order Review - sendEmail()", EX.ToString());
}
}
}
protected void submitBtn(object sender, EventArgs e)
{
if (Page.IsValid)
{
Database db = Factory.GetDatabase("master");
PlaceHolder form = (PlaceHolder)FindControl("form");
PlaceHolder sent = (PlaceHolder)FindControl("sentMsg");
using (new SecurityDisabler())
{
sendEmail();
form.Visible = false;
sent.Visible = true;
}
}
}
}
I think this answer has what you're looking for. Basically, you can use javascript to send the html to the server in order to include it in your email:
asp.net get html controls in code behind
Also, make sure you include a ValidateRequest="false" on the page in order to post back html
if someone else has same problem and the repeater object has no image this solution is simple and easy instead of trust to a client javascript feedback !!
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =new HtmlTextWriter(stringWrite);
Repeater1.RenderControl(htmlWrite);string emailContent = stringWrite.ToString();
I am having Default.aspx Page for Login. After Successful Login it shows the ItemValuation.aspx Page but in the address bar the link shown is Default.aspx. The problem started after I implimented the jquery in my Project. If I remove the jquery
references and Code then link shown is correct after login i.e. ItemValuation.aspx
Can any one tell me how can I solve this Problem? After successful Login on Default.aspx the link shown in address bar should be ItemValuation.aspx For your reference I am posting the Default Page aspx code.
Thanks in Advance.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Item_Valuation.Default" %>
<!DOCTYPE html >
<html >
<head runat="server">
<link rel="shortcut icon" href="~/Images/ACME.ico">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0;"/>
<link href="css/jquery.mobile-1.1.0.min.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.8.18.custom_mini.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.1.0.min.js" type="text/javascript"></script>
</head>
<body >
<div data-role="page" id ="loginpage" data-theme="c" >
<form id="formLogin" runat="server" >
<div id ="DivHeader" data-role="header" data-position="fixed" data-theme="c" >
<div style="text-align:center;top:4px;">
<asp:Image ID="Image1" runat="server"
ImageUrl="Images/ItmVlun.jpg" />
</div>
</div>
<div data-role="content" style=" margin-top: 2px;">
<table style="text-align:right;width:100%">
<tr>
<td style="width:80%" >
<table style="border-color: #FFCC00;width:100%;left:5%; text-align:left;">
<tr>
<td style="width:50%;"><asp:Label ID="lblLogin" runat="server" Text="Login:"
Font-Bold="False" Font-Names="Copperplate Gothic Light" Font-Size="Large"></asp:Label>
</td>
<td style="width:50%;"><input id="txtUserName" type="text" runat="server" style="width:100%;font-size:large;" /></td>
<td><ASP:RequiredFieldValidator ControlToValidate="txtUserName"
Display="Static" ErrorMessage="*" runat="server"
ID="vUserName" /></td>
</tr>
<tr>
<td >
<asp:Label ID="lblPassword" runat="server" Text="Password:" Font-Bold="False"
Font-Names="Copperplate Gothic Light" Font-Size="Large"></asp:Label>
</td>
<td ><input id="txtUserPass" type="password" runat="server" style="width:100%;font-size:large;" /></td>
</tr>
<tr>
<td >
<asp:Label ID="lblRememberMe" runat="server" Text="Remember Me:"
Visible="False" Font-Names="Copperplate Gothic Light"></asp:Label>
</td>
<td >
<asp:CheckBox ID="chkPersistCookie" runat="server" autopostback="false"
Visible="False" />
</td>
<td ></td>
</tr>
</table>
</td>
<td style="width:20%;">
<asp:Image ImageAlign=Right ID="Image2" runat="server"
ImageUrl="~/Images/LogInimg.jpg" Width="100%" Height=60% />
</td>
</tr>
</table>
</div>
<div data-role="footer" data-position="fixed" data-theme="c">
<asp:Button ID="btnLogIn" runat="server" OnClick="LogMe_Click"
Text="Log in" data-theme="a" CausesValidation="False" data-role="button" data-inline="true" style=" float : left;" />
<input type="button" ID="CloseButton" value="Close" onclick ="window.close();" />
<asp:Label ID="lblMsg" runat="server" ForeColor="#FF0066" style=" float : Right;" ></asp:Label>
</div>
</form>
</div>
</body>
</html>
//Default.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
//using System.Web.UI.MobileControls;
using System.Runtime.InteropServices;
namespace Item_Valuation
{
public partial class Default : System.Web.UI.Page
{
// internal static extern int lineGetGeneralInfo(IntPtr hLine, byte[] bCache);
//public static string IMEI;
Item_Valuation.User usr;
public static string message="";
public string AuthorisationMsg;
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
if (Request.QueryString["TCPServer"] != null)
{
AuthorisationMsg = Request.QueryString["TCPServer"].ToString();
GlobalData.SetSettings();
lblMsg.Text = "Error: TCP Server IP " + GlobalData.TCPServer + " " + AuthorisationMsg;
}
else if (Request.QueryString["Message"] != null)
{
lblMsg.Text = Request.QueryString["Message"].ToString();
}
}
txtUserName.Focus();
}
catch (Exception ee)
{
lblMsg.Text = ee.Message;
}
}
private bool ValidateUser(string userName, string passWord)
{
if ((null == userName) || (0 == userName.Length))
{
return false;
}
try
{
string msg = "";
Item_Valuation.User Usr = Item_Valuation.User.CheckLogin(userName, passWord, ref msg);
if (msg.Length > 0)
{
lblMsg.Text = msg;
Response.Write("<script>'alert("+lblMsg.Text +"')</script>");
return false;
}
if (Usr != null)
{
}
else
{
lblMsg.Text = "Invalid Login id or Password";
Response.Write("<script>'alert(" + lblMsg.Text + "')</script>");
return false;
}
}
catch (Exception ex)
{
// AcmePayRollBusiness.PayRollError.PostError(this.GetType(), ex, "Error while validating User");
return false;
}
return true;
}
public void LogMe_Click(object sender, EventArgs e)
{
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect=null;
//strRedirect = Request["ReturnUrl"];
usr = (Item_Valuation.User)HttpContext.Current.Session["User"];
int roleLevel = usr.RoleLevel;
if (roleLevel != 1)
{
if (strRedirect == null)
strRedirect = "ItemValuation.aspx";
}
else
{
if (strRedirect == null)
strRedirect ="PrinterAssignment.aspx";
}
Response.Redirect(strRedirect);
//Server.Transfer(strRedirect);
}
}
}
}
jQuery Mobile is the one that's doing that. By default, it changes all links and form submissions through AJAX.
To disable this... interesting... functionality, you need to add a handler to the mobileinit event, and set ajaxEnabled to false.
Docs here on how exactly to do this: http://jquerymobile.com/demos/1.1.0/docs/api/globalconfig.html
I want to do basic functionality with a simple contact form and on submit the form emails to someone. This is quite easy to do in asp.net, however I am having trouble once I upload it as a user control. Do you have a good example I can look at? Thank you!
It is the same as you would have in a normal asp.net page, the sample assumes you are using the latest version of Sitefinity and that you are have a RadScriptManager or ScriptManager on your master page.
Firstly here is my example form codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.ComponentModel;
public partial class UserControls_LandingPage_contactForm : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
bool bSent = false;
try
{
//create the email and add the settings
var email = new MailMessage();
email.From = new MailAddress(FromEmail);
email.To.Add(new MailAddress(FromEmail));
email.Subject = Subject;
email.IsBodyHtml = true;
//build the body
var sBody = new StringBuilder();
sBody.Append("<strong>Contact Details</strong><br /><br />");
sBody.AppendFormat("Needs: {0}<br />", cboConsultationType.SelectedValue);
sBody.AppendFormat("Name: {0}<br />", txtName.Text);
sBody.AppendFormat("Email: {0}<br />", txtEmail.Text);
sBody.AppendFormat("Number: {0}<br />", txtPhone.Text);
sBody.AppendFormat("Comment: {0}<br />", txtMsg.Text);
email.Body = sBody.ToString();
//send the email
var smtpServer = new SmtpClient();
smtpServer.Send(email);
//mark as sent ok
bSent = true;
}
catch (Exception ex)
{
//send any errors back
//add your own custom handling of errors;
}
//let the end user know if it was a success
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('" + (bSent ? SuccessText : FailureText) + "');", true);
}
//properties
public string FromEmail
{
get { return _fromEmail; }
set { _fromEmail = value; }
}
public string Subject
{
get { return _subject; }
set { _subject = value; }
}
public string SuccessText
{
get { return _successText; }
set { _successText = value; }
}
public string FailureText
{
get { return _failureText; }
set { _failureText = value; }
}
//fields
private string _fromEmail = "info#example.com.au";
private string _subject = "Website Enquiry";
private string _successText = "Thank you for submitting your details we will be in touch shortly.";
private string _failureText = "There was a problem submitting your details please try again shortly.";
}
ASCX Code:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ContactForm.ascx.cs" Inherits="UserControls_LandingPage_contactForm" %>
<fieldset>
<div class="focus">
<label>
I need...</label>
<asp:DropDownList ID="cboConsultationType" runat="server" CssClass="select sub web">
<asp:ListItem Value="I Need A New Web Site">A completely new website</asp:ListItem>
<asp:ListItem Value="Web Site Upgrade">My website upgraded</asp:ListItem>
<asp:ListItem Value="Application Design">An application </asp:ListItem>
<asp:ListItem Value="An ecommerce website">New Ecommerce website</asp:ListItem>
<asp:ListItem Value="Other">Other</asp:ListItem>
</asp:DropDownList>
</div>
<ul>
<li>
<asp:Label EnableViewState="false" ID="lblErrorMessage" runat="server"></asp:Label>
</li>
<li>
<asp:Label EnableViewState="false" ID="lblName" AssociatedControlID="txtName" runat="server"
Text="Name"></asp:Label>
<asp:TextBox ID="txtName" runat="server" ValidationGroup="ContactValidation"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ValidationGroup="ContactValidation"
ControlToValidate="txtName" ErrorMessage="Name is required">*</asp:RequiredFieldValidator>
</li>
<li>
<asp:Label ID="lblPhone" runat="server" AssociatedControlID="txtPhone" EnableViewState="false"
Text="Phone"></asp:Label>
<asp:TextBox ID="txtPhone" runat="server" ValidationGroup="ContactValidation"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorPhone" runat="server" ValidationGroup="ContactValidation"
ControlToValidate="txtPhone" ErrorMessage="Phone is required">*</asp:RequiredFieldValidator>
</li>
<li>
<asp:Label ID="lblEmail" runat="server" AssociatedControlID="txtEmail" EnableViewState="false"
Text="Email"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server" ValidationGroup="ContactValidation"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ValidationGroup="ContactValidation"
ControlToValidate="txtEmail" ErrorMessage="Email is required">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail" runat="server"
ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="ContactValidation" ErrorMessage="Email address is invalid">*</asp:RegularExpressionValidator>
</li>
<li>
<asp:Label ID="lblMsg" runat="server" AssociatedControlID="txtMsg" EnableViewState="false"
Text="How can we assist you?"></asp:Label>
<asp:TextBox ID="txtMsg" runat="server" TextMode="MultiLine" Rows="5" Wrap="true"></asp:TextBox>
</li>
<li>
<asp:Button ID="btnSubmit" runat="server" EnableViewState="false" CssClass="submit"
Text="Send" ValidationGroup="ContactValidation" OnClick="btnSubmit_Click" />
</li>
</ul>
</fieldset>
Then the only other items you need to be wary of is in the web.config you need to modify the system.net settings for email:
<system.net>
<mailSettings>
<smtp from="mailmaster#yourdomain.com">
<network host="smtp.yourdomain.com" userName="Your_Username" password="Your_Password" port="25" />
</smtp>
</mailSettings>
</system.net>
Then upload the control or modify your web.config . Then provided your SMTP server is all set up correctly the form should send no problem.
I hope this helps you out.
I think one good approach is using the incorporated mail sender. The profits are that you can configure the settings inside the Administration->Settings->Advanced->System->SMTP
var smtpSettings = Config.Get<SystemConfig>().SmtpSettings;
MailMessage message = new MailMessage();
message.From = new MailAddress(smtpSettings.UserName);
message.To.Add(new MailAddress(toEmail));
StringBuilder sb = new StringBuilder();
sb.AppendFormat(body);
message.Subject = subject;
message.Body = sb.ToString();
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.Unicode;
message.SubjectEncoding = Encoding.Unicode;
EmailSender.Get().Send(message);
You can use notifications too.