try-catch in .NET execute jQuery script - c#

After sucessfull sending mail with asp.net I want to execute jQuery script
.NET Code:
void btnSubmit_Click(Object sender, EventArgs e) {
MailMessage objEmail = new MailMessage();
objEmail.To = "mymail#com";
objEmail.From = txtFrom.Text;
objEmail.Cc = txtCc.Text;
objEmail.Subject = "Contact";
objEmail.Body = "note: " + txtComments.Text + " <br> " + "name:" + txtName.Text;
objEmail.Priority = MailPriority.High;
objEmail.BodyFormat = MailFormat.Html;
SmtpMail.SmtpServer = "localhost";
try{
SmtpMail.Send(objEmail);
Response.Write("Email send");
}
catch (Exception exc){
Response.Write("");
}
}
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
var par = $('.x');
$(par).hide();
$("button").click(function(){
$(".x").toggle();
});
});
</script>
Both scripts works perfecty, but I have no idea how to combine them in order to close contact form after successful sending mail.
Here is whole contact form:
<div align="center"><button class="button">Napisz do nas!</button></div>
<div class="x">
<form runat="server">
<div align="center">
<table border="0" width="350">
<tr>
<td valign="top"><font face="Verdana" size="2">Imię i Nazwisko:</font></td>
<td height="20"> <asp:TextBox runat="server" Height="21px" Width="215px" ID="txtName"></asp:TextBox>
<br>
<asp:RequiredFieldValidator ID = "req1" ControlToValidate = "txtFrom" Runat = "server" ErrorMessage = "Proszę podać Imię i Nazwisko "></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td valign="top"><font face="Verdana" size="2">E-mail:</font></td>
<td height="24"> <asp:TextBox runat="server" Height="22px" Width="213px" ID="txtFrom"></asp:TextBox>
<br>
<asp:RegularExpressionValidator ID = "reg1" ControlToValidate = "txtFrom" Runat = "server" ErrorMessage = "Invalid Email" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator> <asp:RequiredFieldValidator ID = "req3" ControlToValidate = "txtFrom" Runat = "server" ErrorMessage = "Nieprawidłowy Email" ></asp:RequiredFieldValidator></td>
</tr>
<!--<tr>
<td valign="top"><font face="Verdana" size="2">To</font></td>
<td height="24" valign="top">
<asp:TextBox runat="server" Height="22px" Width="212px" ID="txtTo"></asp:TextBox>
<br>
<asp:RegularExpressionValidator ID = "reg2" ControlToValidate = "txtTo" Runat = "server" ErrorMessage = "Invalid Email" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID = "req4" ControlToValidate = "txtTo" Runat = "server" ErrorMessage = "Please enter recipients E-mail" ></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td valign="top"><font face="Verdana" size="2">Cc</font></td>
<td height="24" valign="top">
<asp:TextBox runat="server" Height="22px" Width="210px" ID="txtCc"></asp:TextBox>
<br>
<asp:RegularExpressionValidator ID = "reg3" ControlToValidate = "txtCc" Runat = "server" ErrorMessage = "Invalid Email" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>-->
<tr>
<td valign="top"><font face="Verdana" size="2">Wiadomość:</font></td>
<td height="80"> <asp:TextBox runat="server" Height="80px" TextMode="Multiline" rows="4" Width="258px" ID="txtComments"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" valign="top" height="10" align="center">
<asp:Button Runat = server ID = btnSubmit OnClick = btnSubmit_Click Text = "Wyślij"></asp:Button>
<input type = "reset" runat = "server" value = "Wyczyść"></td>
</tr>
</table>
</div>
</form>
</div>

Most of the time when I need to do this, I place the javascript code in a asp.net placeholder control, which I set to be invisible at page load, and change it to visible when I need to execute the javascript.
This would also allow you to handle the try, catch and finally statements by doing it with 3 different placeholders...

What you have to remember is that the .NET code runs on the server and the jQuery code runs in the browser. There is no direct way to "call" JavaScript from .NET.
You can use the ClientScript property of the page object to inject the JavaScript into your page so that when the new page gets rendered into the browser it will contain the script and execute it.
http://msdn.microsoft.com/en-us/library/btf44dc9(v=vs.110).aspx

<div id="x" runat="server">
<!-- your html -->
</div>
In case of successful send of email of the btnSubmit_Click:
x.Visible = false;

Related

Trying to Send Email via SMTP - Sample Message Keeps Appearing

I'm trying to send an email using SMTP.
I have an HTML form on a page that runs a server-side script (code for both below). The two Selects get their choices from a SharePoint list. I don't believe the code is relevant as that's all it does, but I can edit and paste in if need be.
Every time I hit submit on the form, all I get is a new email appearing on my screen with "Sample" in the body and no other fields populated. Any ideas why this is?
I am aware I'm not seeing values from the form, that's not the issue. The issue is that I'm specifying To, From, Subject and Body in the C# method and not seeing those in the email.
HTML Form
<div>
<table class="frm">
<th colspan="2" style="background-color: #e6e6e6; font-size: 2em">
<b>Helpdesk Ticket Form</b>
</th>
<tr>
<td>
<b>Subject</b>
</td>
<td>
<input type="text" id="subject" style="width: 96%;"></input>
</td>
</tr>
<tr>
<td>
<b>Urgency</b>
</td>
<td>
<select id="urgency" style="width: 100%;"></select>
</td>
</tr>
<tr>
<td>
<b>Impact</b>
</td>
<td>
<select id="impact" style="width: 100%;"></select>
</td>
</tr>
<tr>
<td>
<b>Description</b>
</td>
<td>
<textarea id="description" cols="40" rows="5"></textarea>
</td>
</tr>
<tr>
<td colspan="2">
<button id="A1" runat="server" onclick="SendEmail();">Submit</button>
</td>
</tr>
</table>
</div>
C# Method
public void SendEmail()
{
try
{
SmtpClient client = new SmtpClient("mysmtpclient");
client.UseDefaultCredentials = true;
MailAddress from = new MailAddress("MyEmail#email.com");
MailAddress to = new MailAddress("TheirEmail#email.com");
MailMessage message = new MailMessage(from, to);
message.Subject = "Test";
message.Body = "<b>Test message!</b>";
message.IsBodyHtml = true;
client.Send(message);
}
catch (Exception ex)
{
//it done broked
}
}

ASP Login and Logout Help for Beginner

Question 1: Login page - I want a popup to occur that says to re-enter credentials if the user puts in the wrong info.
Question 2: Logout Function - I need to end the users session when they click the logout button. Can someone please tell me exactly what to put in the Logout.aspx.cs and the Logout.aspx pages?
Code behind for Login page:
protected void btnLogin_Click1(object sender, EventArgs e)
{
ThisWS.Client client = new ThisWS.Client();
//client.Endpoint.Address = new System.ServiceModel.EndpointAddress("https://svcThisService.svc/soap");
WSAccess.ThisWS.clsTypesAuthResult response = client.Auth(this.txtUsername.Text, this.txtPassword.Text, txtAuthCode.Text);
client.Close();
this.lblErrorMessage.Text = response.Error;
this.lblToken.Text = response.Token.ToString();
int?[] cases = response.CaseNum;
//Session.Add("Username", this.txtUsername.Text); //User must re-login after an hour, since the token expires.
//Session.Add("Password", this.txtPassword.Text);
//Session.Add("AuthCode", this.txtAuthCode.Text);
Session.Add("Token", response.Token);
Session.Add("TokenExpires", DateTime.Now.AddHours(1));
Session.Add("Cases", cases);
Session.Add("PartyNameId", response.PartyNameID);
Response.Redirect("ListCases.aspx");
.ASPX code I have for the login form:
<p class="redtext">Please use the form below to login.</p>
<div class="">
<form id="form1" runat="server">
<div>
<table class="auto-style1">
<tr>
<td class="auto-style2">Your Username:</td></tr>
<tr>
<td>
<asp:TextBox ID="txtUsername" runat="server" Width="241px" MaxLength="255"></asp:TextBox>
</td>
<td> </td>
</tr>
<td> </td>
<tr>
<td class="auto-style2">Your Password:</td></tr>
<tr>
<td>
<asp:TextBox ID="txtPassword" runat="server" Width="239px"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style2" hidden="hidden">Authentication code: </td>
<td>
<asp:Label ID="txtAuthCode" runat="server" Width="244px" Visible="False">000</asp:Label>
</td>
<td> </td>
</tr>
<tr>
<td>
<asp:Button ID="btnLogin" runat="server" Text="Click Here to Login" class="btn btn-primary btn-block" Width="175px" OnClick="btnLogin_Click1" />
</td>
<td> </td>
</tr>
</table>
</div>
</form>
</div>
1) Use a function that has an alert in the OnClick event of the login Button. I would use a javascript function to verify the credentials, then alert if the credentials are incorrect
e.g.
<asp:Button ID="btnLogin" runat="server" Text="Click Here to Login" class="btn btn-primary btn-block" Width="175px" OnClick="verifyCredentials()" />
In the JavaScript:
function verifyCredentials() {
if ( credentials != correctCredentials ) {
alert('Please Enter Correct Credentials')
else
//proceed
Best Practice is not to use the OnClick event however. Using event listeners in JavaScript or binding events using jQuery:
JavaScript:
element.addEventListener(type, handler, false);
jQuery
$('#btnLogin').click(function() { ..... });
If you do not have JavaScript experience, go to this link: http://www.w3schools.com/js/DEFAULT.asp
This should help you become more familiar with the language and uses.
2) I'm not too familiar, but the solutions have been covered extensively on StackOverflow. Here are some links that should point you in the right direction:
How to kill the Session of User when he LoggedOut in ASP.NET
How to end the user session and make sure that the user is logged out?

Unable to disable text box using javascript

I've following login form which has two HTML5 text boxes with required valdation:
<div id="SignUpForm" class="loginContainer">
<div style="width: 100%; height: 20px">
<div class="triangle">
</div>
</div>
<table class="loginForm" align="left">
<tr>
<td align="left" class="style1">
<input id="txtCustEmailID" type="email" name="txtCustEmailID" placeholder="Enter Email ID"
required style="width: 195px" />
</td>
<td align="left">
<asp:Button ID="btnCustLogin" runat="server" Text="Sign Up" OnClick="btnCustLogin_Click" />
</td>
</tr>
<tr>
<td align="left" class="style1">
<input id="txtCustPwd" name="txtCustPwd" type="password" required placeholder="Enter Password"
style="width: 193px" />
</td>
<td align="left">
<input id="btnCancel" type="button" value="Cancel" onclick="cancel('txtCustEmailID','txtCustPwd','SignUpForm')" />
</td>
</tr>
<tr>
<td colspan="2" align="left" style="font-size: medium; color: #FFFFFF;">
<a href="#RegOnSrchdialog" name="modal" style="color: #FFFFFF; font-weight: bold"
onclick="EnableRegFormTxt('txtCustEmailID','txtCustPwd','SignUpForm')">Register</a>
</td>
</tr>
</table>
</div>
On clicking the anchor tag "Register" I am calling a javascript function EnableRegFormTxt which I am using to disable the login form textboxes so that their validations will also get disabled, but this js is not working and I am not able to do any post back on the page because of validations.
The js is:
function EnableRegFormTxt(i, j, k) {
document.getElementById("txtCustFName").disabled = false;
document.getElementById("txtCustLName").disabled = false;
document.getElementById("txtCustREmail").disabled = false;
document.getElementById("txtCustRPwd").disabled = false;
document.getElementById("txtCustRePwd").disabled = false;
document.getElementById("txtCustPh").disabled = false;
document.getElementById(i).disabled = true;
document.getElementById(j).disabled = true;
document.getElementById(k).style = "display:none";
}
Please let me know where I am wrong.
Thanx.
Hope this helps:
function makeReadOnly()
{
document.getElementById("TextBox1").readonly=true;
}
Call above function on click event or any other event you want.
Here is your function:
function EnableRegFormTxt(i, j, k) {
document.getElementById("txtCustFName").readonly = false;
document.getElementById("txtCustLName").readonly = false;
document.getElementById("txtCustREmail").readonly = false;
document.getElementById("txtCustRPwd").readonly = false;
document.getElementById("txtCustRePwd").readonly = false;
document.getElementById("txtCustPh").readonly = false;
document.getElementById(i).readonly = true;
document.getElementById(j).readonly = true;
document.getElementById(k).style = "display:none";
}
you can try this:
function DisableRegFormTxt(i, j, k) {
document.getElementById("txtCustFName").setAttribute('readonly');
document.getElementById("txtCustLName").setAttribute('readonly');
document.getElementById("txtCustREmail").setAttribute('readonly');
document.getElementById("txtCustRPwd").setAttribute('readonly');
document.getElementById("txtCustRePwd").setAttribute('readonly');
document.getElementById("txtCustPh").setAttribute('readonly');
}
function EnableRegFormTxt(i, j, k) {
document.getElementById("txtCustFName").removeAttribute('readonly');
document.getElementById("txtCustLName").removeAttribute('readonly');
document.getElementById("txtCustREmail").removeAttribute('readonly');
document.getElementById("txtCustRPwd").removeAttribute('readonly');
document.getElementById("txtCustRePwd").removeAttribute('readonly');
document.getElementById("txtCustPh").removeAttribute('readonly');
}

how to get label text inside repeater

I am trying to get the text of a lable when someone clicks on a link button:
this is my code :
$(document).ready(function () {
$('[id*="lnkbtn_Remove"]').click(function (event) {
event.preventDefault();
var id = $("span[id*=lbl_Reference]").text();
alert(id);
});
});
But this gets me all the reference in the reapter as I am using "*". Is there anyway to get the actual reference on the row it has been clicked. Here is my html:
<asp:Repeater ID="rpt" runat="server" >
<ItemTemplate>
<div class="test">
<table>
<tr>
<td>
<div style="width: 230px;">
<asp:Label ID="lbl_Len" runat="server" CssClass="font_bold"></asp:Label>
<br />
<asp:Label ID="lbl_Reference" runat="server"></asp:Label>
</div>
</td>
<td align="left">
<div style="width: 80px;">
<asp:LinkButton ID="lnkbtn_Remove" runat="server" CssClass="rpt_item_Remove">Remove</asp:LinkButton>
</div>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
You can get it by something like this,
var lablelId = $(this).closest('.test').find('[id*=lbl_Reference']).attr('id');
var lablelText = $(this).closest('.test').find('[id*=lbl_Reference]').text();
If you want to find how many column set checked and if checked then want to find label value that nested inside repeater table row PFB :-
var chkValue = $("#TableID [id*=chkBoxId]");
for (var i = 0; i < chkValue.length; i++) {
if (chkValue[i].checked)
$('#TableID tr:eq(' + (i+1) + ') td:eq(0)').find('[id*=lblIds]').text() ;

Popup does not work sometimes when a button is clicked. where is the problem at? -Asp.net

Why do popup does not work sometimes. There is no condition for popup. Whenever a button is clicked, it has to pop. Where do you guys think the problem might be??
Thanks,
<table id="pnlPopupAdditional" runat="server" style="display:none">
<tr>
<td>
<asp:Panel runat="server" CssClass="modalPopup">
<table width="350" height="80" class="warningPopup">
<tr>
<td>
<!-- <img src="images/warning_blue.gif" alt="Warning" /> -->
</td>
<td colspan="2" align="left" style="padding-left: 75px; padding-top: 10px;">
<asp:Literal ID="ltMessage" runat="server"></asp:Literal>
</td>
</tr>
<tr>
<td align="center" colspan="4">
<input id="btnYesAdditional" type="button" value="YES" class="popupButton" />
<input id="btnNoAdditional" type="button" value="NO" class="popupButton" />
</td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
</table>
<asp:Button ID="btn" runat="server" Visible="false" />
private void SetAdditionalLocationMessage()
{
_AccountSummary accountSummary = new _AccountSummary();
accountSummary = new Merchant2().GetAccountSummary(MerchantID);
if (accountSummary != null)
{
if (accountSummary.PackageID != (int)CommonHelper.Package.Free )
btnAdd.Visible = true;
else
btnAdd.Visible = false;
}
if (new Merchant2().IsLocationCountExceed(MerchantID))
{
string locationFee = new Merchant2().GetAdditionalLocationFee(accountSummary.PackageID).ToString();
ltMessage.Text = String.Format(ApplicationData.MSG_ADDITIONAL_LOCATION_CHARGE, locationFee);
ModalPopupExtender1.TargetControlID = "btnAdd";
ConfirmButtonExtender1.TargetControlID = "btnAdd";
}
else
{
ModalPopupExtender1.TargetControlID = "btn";
ConfirmButtonExtender1.TargetControlID = "btn";
}
//Controls_UC
protected void btnAdd_Click(object sender, ImageClickEventArgs e)
{
MerchantID = CommonHelper.GetLoggedInMerchant();
string QueryString = ApplicationData.URL_MERCHANT_COMPANY_PAYMENT + "?MerchantProfilePages";
Response.Redirect(QueryString);
It may be a result of JavaScript referenced DOM elements being disposed of during an AJAX request.
This is assuming you are acquiring a JavaScript reference of the DOM element referenced via pnlPopupAdditional.ClientID, so that you may modify the display:none; style declaration.

Categories