Call Server Side Function On HTML Button Click - c#

I have one button when i click on it... first my DIV gets execute/loaded which is working fine for me.
Now parallel i want to send an email to my account how i can call my server side function. Means when Admin click on "Mail Account Detail" i want to pop up DIV as well as Call my Server Side function names "SendAnEmail".
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#patPortalCredDiv">Mail Account Detail</button>
Here is my Div Code.
<div id="patPortalCredDiv" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" style="color: black;">Mail Credential</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="form-group">
<h4 for="UserName">Note:-
<asp:Label type="text" runat="server" Text="" ID="txtMail"></asp:Label>
</h4>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Here is my server side function which i want to call also.
protected void SendAndEmail(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Server Side Code Also executed.');", true);
}

Problem in this case were data-toggle and data-target attributtes preventing page to post back.
In your aspx page replace your button for this:
<asp:Button Text="Mail Account Detail" OnClick="SendAndEmail"
CssClass="btn btn-primary" type="button" runat="server" />
In your C# code behind
protected void SendAndEmail(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert",
"$('#patPortalCredDiv').modal('show');", true);
}
This will open bootstrap modal using jQuery

This is what I have done.
I am using HTML and Java for the back-end to send the mail.
<body>
<h3> Please Enter your Email Address </h3>
<form action="Sendmail" method="post">
<input type="text" class="form-control" placeholder="staff_email" email="staff_email">
<input type="submit" value="Submit">
</form>
</body>
On the back end side, I am using Gmail service.
public class EmailUtility{
public static void sendEmail(String host, String port,
final String senderEmail, String senderName, final String password,
String recipientEmail, String subject, String message) throws AddressException,
MessagingException, UnsupportedEncodingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, password);
}
};
Session session = Session.getInstance(properties, auth);
//creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(senderEmail));
InternetAddress[] toAddresses = { new InternetAddress(recipientEmail) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
//sends the e-mail
Transport.send(msg);
}
}
I am using Tomcat Server. Please add the following lines in the web.xml of Tomcat Server.
<context-param>
<param-name>email</param-name>
<param-value>abc#gmail.com</param-value>
</context-param>
<context-param>
<param-name>name</param-name>
<param-value><Your Name></param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value> Your Password Comes Here </param-value>
</context-param>

Related

PartialView is returning fullpage, only rendering the form

I'm trying to rerender the partialview ONLY in my modal, after the ajax request.
But when I get the response everything is rerendered and the only thing showing is the partialview..
PartialView:
#{
var bidModel = new BidModel();
}
<div>
<div class="row">
#if (ViewBag.Message != null)
{
<div class="alert alert-success">#ViewBag.Message</div>
}
</div>
<span class=" alert-danger">
#Html.ValidationSummary()
</span>
<div class="form-group">
<input name="Bidder" asp-for="#bidModel.Bidder" value="#User.Identity.Name" type="hidden" />
<input name="AuctionId" asp-for="#bidModel.AuctionId" type="hidden" id="auctionId" />
<label asp-for="#bidModel.Amount" />
<input name="Amount" asp-for="#bidModel.Amount" />
</div>
</div>
Controller:
public async Task<IActionResult> AddBid(BidModel Bid)
{
var result = await _bidBusinessInterface.CreateBidAsync(Bid, Bid.AuctionId);
if (result)
{
ViewBag.Message = "Bud lagt!";
}
else
{
ViewBag.Message = "Bud förlågt!";
}
return PartialView("_BidCreatorPartial");
}
And then we have the modal where i want to rerender the partialview:
<div class="modal fade" id="bidModal" tabindex="-1" role="dialog" aria-labelledby="bidModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="bidModalLabel">Lägg bud</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form asp-action="AddBid" asp-controller="Home" method="POST" data-ajax="true" data-ajax-update="frmBid">
<div id="frmBid">
<partial name="_BidCreatorPartial" model="#bidModel"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Avbryt</button>
<button type="submit" class="btn btn-primary">Spara</button>
</div>
</form>
</div>
</div>
</div>
</div>
As I said, what I want to accomplish is to rerender the form, so that the message can be shown in the modal.
What happens is it renders a whole white page with only the form and the message.
You didn't actually post your form itself, but my best guess is that you're just doing a standard old HTML form post. That's always going to cause the page to change, and then since you're only returning a partial view, and not a full view, your page gets replaced with just that snippet of HTML.
What you want requires AJAX. You need to catch the submit event on the form, and instead of letting it go as normal, you make an AJAX request with the form data serialized. Then, in the success callback of your AJAX request, you'll need to query the element you want to replace the HTML of from the DOM and change its innerHTML value to what's returned from the AJAX request.
Since an ASP.NET Core project comes with jQuery out of the box, I'm going to assume you can use that:
$('#MyForm').on('submit', function (e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr('action'),
method: 'post',
data: $form.serialize(),
success: function (html) {
$('#frmBid').html(html);
}
});
});

Prevent multiple clicks on bootstrap modal button with ASP.NET

I use boostrap modals for saving data on an ASP.NET Web page and I'm having an issue when users by mistake clicks more than once the "Save" button on the modal. The event fires the number of times the user presses the click. This happens because the modal doesn't closes immediatly. It takes about 1 second to close, enough for the user to click more than once the button.
My database is validated (I'm using Entity Framework) so, there's no duplicate values inserted. But if the user clicks two times, it tries to insert the record two times, and the error message is displayed.
How can I prevent this?
This is the modal code:
<asp:Panel runat="server" ID="pnlBank" DefaultButton="btnSaveBank">
<div class="modal fade" id="modBank" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h4 class="modal-title">Banco</h4>
</div>
<div class="modal-body">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div class="form-group">
<div class="row">
<label class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<asp:TextBox ID="txtBankName" CssClass="form-control" runat="server" MaxLength="150"></asp:TextBox>
</div>
</div>
<label class="col-md-2 control-label">Address</label>
<div class="col-md-10">
<asp:TextBox ID="txtBankAddress" CssClass="form-control" runat="server" MaxLength="150"></asp:TextBox>
</div>
</div>
<div class="row">
<label class="col-md-2 control-label">Phone</label>
<div class="col-md-10">
<asp:TextBox ID="txtBankPhone" CssClass="form-control" runat="server" MaxLength="15"></asp:TextBox>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="modal-footer">
Cerrar
<asp:Button ID="btnSaveBank" runat="server" Text="Save" CssClass="btn btn-primary" OnClick="btnSaveBank_Click" />
</div>
</div>
</div>
</div>
</asp:Panel>
And this is the code behind:
protected void btnSaveBank_Click(object sender, EventArgs e)
{
Bank newBank = new Bank();
newBank.Name = txtBankName.Text;
newBank.Address = txtBankAddress.Text;
newBank.Phone = txtBankPhone.Text;
using (bankEntity)
{
try
{
bankEntity.Bank.Add(newBank);
bankEntity.SaveChanges();
lblResult.Text = "Bank successfully saved";
ObtenerBancos();
}
catch (Exception ex)
{
lblResult.Text = "Error when saving bank: " + ex.Message;
}
}
}
You can try disabling the save button and closing the modal via jQuery and once the modal is closed you can re-enable the save button again using jQuery. Just make sure that the jQuery event handlers are defined after btnSaveBank_Click so that btnSaveBank_Click takes precedence over the close/hide trickery:
$(document).ready(function () {
$("#btnSaveBank").click(function() {
$(this).prop("disabled", true);
$("#modBank").modal("hide");
});
$("#modBank").on("hidden.bs.modal", function() {
$("#btnSaveBank").prop("disabled", false);
});
});

How to email Modal

I'm fairly new to asp .net MVC, I've got a modal wish accepts a username, email address, comments, and also has a submit button. I'm looking create the submit functionality such that when it's pressed it'll send an email.
I've had passed experience sending emails in c# no problem, the troubles I'm having is linking the two together.
<div class="modal fade" id="contact" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal">
<div class="modal-header">
<h4>Contact Tech Site</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="contact-name" class="col-lg-2 control-label">Name:</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="contact-name" placeholder="Full Name">
</div>
</div>
<div class="form-group">
<label for="contact-email" class="col-lg-2 control-label">Email:</label>
<div class="col-lg-10">
<input type="email" class="form-control" id="contact-email" placeholder="you#example.com">
</div>
</div>
<div class="form-group">
<label for="contact-msg" class="col-lg-2 control-label">Message:</label>
<div class="col-lg-10">
<textarea class="form-control" rows="8"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal">Close</a>
<button class="btn btn-primary" type="submit">Send</button>
</div>
</form>
</div>
</div>
</div>
Email Code
var SMTP_USERNAME = User.EmailUsername;
var SMTP_PASSWORD = EncryptionHelper.Decrypt(User.EmailPassword);
Mail.Subject = Subject;
Mail.Body = EmailText;
foreach (var to in SelectedUsers)
{
foreach (var contactMethod in to.ContactMethods.Where(x => x.Primary && x.Channel == ContactMethod.Channels.Email))
{
Mail.To.Add(contactMethod.Value);
}
}
Mail.From = new MailAddress(SMTP_USERNAME, User.FullName());
//Server
var HOST = unitOfWork.SettingRepository.GetString(KnownKeys.SMTPServer);
//Port
var PORT = int.Parse(unitOfWork.SettingRepository.GetString(KnownKeys.SMTPPort));
// Create an SMTP client with the specified host name and port.
var emailSent = false;
using (SmtpClient client = new SmtpClient(HOST, PORT))
{
// Create a network credential with your SMTP user name and password.
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
// Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
// the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
client.EnableSsl = true;
// Send the email.
try
{
client.Send(Mail);
emailSent = true;
}
catch (Exception ex)
{
MessageBox.Show("Error message: " + ex.Message);
}
}
Create a model -
public class EmailViewModel
{
public string Username { get; set; }
public string Email { get; set; }
public string Comments { get; set; }
}
And then create your controller -
public class HomeController : Controller
{
public ActionResult GetEmailForm()
{
return View();
}
public ActionResult SubmitEmail(EmailViewModel model)
{
var result = SendEamil(model);
return View();
}
private bool SendEamil(EmailViewModel model)
{
// Use model and send email with your code.
return true;
}
}
Basically GetEmailForm action will return you a view with form -
#model MvcApplication1.Controllers.EmailViewModel
#{
ViewBag.Title = "GetEmailForm";
}
<h2>GetEmailForm</h2>
<link href="../../Content/bootstrap.css" rel="stylesheet" />
#using (Html.BeginForm("SubmitEmail", "Home", FormMethod.Post))
{
<div id="contact">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal">
<div class="modal-header">
<h4>Contact Tech Site</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="contact-name" class="col-lg-2 control-label">Name:</label>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Username, new { #placeholder = "Full Name"})
</div>
</div>
<div class="form-group">
<label for="contact-email" class="col-lg-2 control-label">Email:</label>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Email, new { #placeholder = "you#example.com"})
</div>
</div>
<div class="form-group">
<label for="contact-msg" class="col-lg-2 control-label">Message:</label>
<div class="col-lg-10">
#Html.TextAreaFor(m => m.Comments, new { #placeholder = "Comments"})
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal">Close</a>
<button class="btn btn-primary" type="submit">Send</button>
</div>
</form>
</div>
</div>
</div>
}
When you enter data and click on submit, it will post the viewmodel with data to SubmitEmail action of same controller.
Output of the page is as shown below, sorry for styles, i have no time so removed some of the styles.
When you enter data and click on submit, you get data as shown below -
Once you have the data, you can use that in your private method SendEmail (which will have your code) to send email.
Check the MSDN site for information on how to create a form, it will get submitted when the user presses the submit button. Back in yoru controller add a second version of your method with the HttpPost attribute and give it a parameter instance of your model, MVC will take care of the mapping for you. See BUILDING ASP.NET MVC FORMS WITH RAZOR for more details.
Call a action method From your Email Controller thru a ajax call.From the below Code Snippet you will get an idea how to do it.
$('#btnSubmit').on('click', function () { //Ur Button
$.ajax({
type: "POST",
url: "/EmailController/SendEmailAction",
data: "{Email:" + $("#contact-email").val() +"}", // Reading from extboxes and Converting to JSON for Post to EmailController Action
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
//alert message
//Close the Modal
}
});
});
And In C# level in youecontroller
public JsonResult _SendEmail(EmailViewModel model)
{
//Here your code to send Email
}
I hope now you will get an idea how to go about it.
I think you do not require a form and submit button to send an email from a bootstrap modal.

Bootstrap Modal - Add server code ASP.Net

Net webform application implementing Bootstrap. Currently I have a label and a text box displayed in Bootstrap - Modal to which Im trying to send the data from the server c# file. For some reason the Modal disappears and doesnt show anything on the UI.
ASPx file
<!-- Button to trigger modal -->
Launch demo modal
<%--<asp:Button ID="Button1" role="button" type="button" runat="server" Text="Modal" class="btn btn-lg btn-success" data-toggle="modal" data-target="#myModal"/>--%>
<!-- Modal -->
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
C# file
protected void Click_Me(object sender, EventArgs e)
{
Label1.Text = "test label";
TextBox1.Text = "text box text";
modal_Img.Src = "test path";
}
Please advice
ps : do i need to use an Update panel ?
An Update Panel would likely not be the best solution for this because only a partial amount of the html is updated and the Javascript/Jquery for the modal is not being called again after the partial postback.
You need some way of invoking the Javascript again after the postback. You could invoke the Javascript needed to open the modal on your Click_Me event.
protected void Click_Me(object sender, EventArgs e)
{
// do stuff
Label1.Text = "test label";
TextBox1.Text = "text box text";
modal_Img.Src = "test path";
// make sure the modal opens
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "script", "<script type='text/javascript'>$( document ).ready(function() { $('#MyModal').modal('show')});</script>", false);
}

How to display data in Bootstrap Modal when link button click in ASP.NET

How to display data in Bootstrap Modal when link button click in ASP.NET. In my code
When i click on link button Modal is opening, but assign values are not displaying. Please tell me how to display modal with assigned values.
Thanks.
.aspx Code:
<asp:LinkButton ID="linkButton8" runat="server" data-toggle="modal" data-target="#myModal" OnClick="linkButton_Click">CIS Information</asp:LinkButton>
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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="myModalLabel" align="center">Candidate Information Sheet</h4>
</div>
<div class="modal-body">
<table class="table table-bordered" align="center">
<tr>
<td>Name</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
<td>Email</td>
<td>
<asp:TextBox ID="txtEnail" runat="server"></asp:TextBox></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-primary" data-ismiss="modal">Close</button>
</div>
</div>
</div>
</div>
C# Code:
protected void linkButton_Click(object sender, EventArgs e)
{
txtName.Text = "Name";
txtEnail.Text = "Mail#gmail.com";
}
Remove the data-toggle and update the code behind to be like this:
protected void linkButton_Click(object sender, EventArgs e)
{
txtName.Text = "Name";
txtEnail.Text = "Mail#gmail.com";
Page.ClientScript.RegisterStartupScript(GetType(), "modelBox", "$("#myModal").modal('show');", true);
}
It is better though to make the link button has a client side click event that gets the data through ajax, set the textboxs values and use the same modal('show') JavaScript function to display the modal box, this will be more efficient and user friendly.
Try adding UseSubmitBehavior="false" and using an asp:button instead.
<asp:Button ID="btnModal" runat="server" data-toggle="modal" data-target="#myModal" OnClick="linkButton_Click" UseSubmitBehavior="false">CIS Information</asp:Button>
The UseSubmitBehavior attribute determines whether the Button uses the browsers submit functionality or ASP.NET postback. By default it is set to true.
Edit
Due to linkButton not having the "UseSubmitBehavior" property.

Categories