Webmail confirmation without new page - c#

I have used this method: http://www.asp.net/web-pages/overview/getting-started/11-adding-email-to-your-web-site
to allow website users to submit Name and Email.
Using this method I have a simple form on one page, which then opens a new page to process the form, sends the email and returns a success message. This works fine in itself, but I would prefer to avoid opening the new page for processing.
(I tried putting all the code on the start page, but then it sends a mail whenever the page loads)
I would much prefer to either replace the form's div with the success message, or pop up a modal with the success message, but I'm not sure how to go about doing this.
I tried putting the processing code in a modal (bootstrap 3), but I don't know how to pass the variables (user input) to the modal (modal being in a separate file to avoid the aforementioned sending on page load behavior)
The processing page (ProcessRequest.cshtml) is as follows:
#{
var customerName = Request["customerName"];
var customerEmail = Request["customerEmail"];
var sub = Request["sub"];
var errorMessage = "";
var debuggingFlag = false;
try
{
// Send email
WebMail.Send(to: "email#hotmail.com",
subject: "Form submitted on HMD. Name: " + customerName + " Email: " + customerEmail,
body: "Submitted details: " + Environment.NewLine + "Name: " + customerName + Environment.NewLine + "Email: " + customerEmail + Environment.NewLine + "Subscribe: " + sub, isBodyHtml: false
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
}
<p>Thankyou for submitting your email, <b>#customerName</b>.
Back
And the form itself is as follows:
<form class="form-inline" method="post" action="~/ProcessRequest.cshtml">
<div class="form-group col-xs-9">
<input type="text" placeholder="Name" name="customerName" class="form-control txt-primary clearable" />
</div>
<div class="form-group col-xs-9">
<input type="email" placeholder="e-mail" id="customerEmail" name="customerEmail" class="form-control txt-primary clearable" />
</div>
<button type="submit" value="submit" data-target="#modal" class="test input-append btn btn-primary col-xs-2"><span class="glyphicon glyphicon-ok"></span></button>
<div class="form-group col-xs-12">
<input id="checkbox" type="checkbox" name="sub" value="Yes" checked/> Subscribe to newsletter
</div>
</form>
I would greatly appreciate any advice on how to achieve this!
I'm not sure whether I should be trying to use AJAX or some other method, I've yet to learn how to use AJAX so if this would be my best option, a pointer to a decent (preferably comprehensible for beginners) tutorial would be nice :)
UPDATE
Ok, So I am attempting to use an iframe as suggested... But so far have not been able to get the data to submit.
I've not used iframe before, so I'm not sure what I'm doing!
I have added a hidden iframe like so:
<iframe class="hidden" name="iframe_submit"></iframe>
I'm not sure where I should be pointing the form at the iframe.
Previously I had the action of the form pointing at ProcessRequest.cshtml.
I have changed this to formtarget="iframe_submit" is this correct?
I changed the submit button to use a href="~/ProcessRequest....
Now the email is being sent, so the iframe must be loading the ProcessRequest page, however the information from the form is not inserted in the email.

Thanks #mplungjan this worked nicely..
Solution: Hidden iframe
<iframe class="hidden" name="iframe_submit"></iframe>
with
<form class="form-inline" method="post" target="iframe_submit" action="~/ProcessRequest.cshtml">...</form>
and added to the ProcessRequest file:
<script>alert("Thankyou for submitting your email, #customerName.")</script>
Your assistance is very much appreciated, especially since I learnt a new trick!

Related

How to pass textbox value using #Url.Action in ASP.NET MVC Core 2.2

In my View i have the following code:
<input type="text" id="createdDate" placeholder="dd/mm/yyyy" />
Download
In my Control i have de following code:
[HttpGet]
public async Task<IActionResult> GetRoomAccessHistory(DateTime createdDate)
{
// TO DO
}
In this particular case, i want to pass the createdDate value that is inside the textbox (createdDate) to my Url.Action(...), so it could be passed as a queryString in my URL.
This action is invoked as a GET request, and in GetRoomAccessHistory control method, i should get my createdDate.
Thank you.
PS
I think the solution should be something like this:
<a href="#Url.Action("GetRoomAccessHistory", "Files", new { createdDate = ??? })" >Download</a>
I have got a possible answer:
<form method="post" enctype="multipart/form-data" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
...
<button type="button" id="downloadRoomAccessHistory"</button>
</form>
<script>
var form = document.getElementById("formGetRoomAccessHistory");
document.getElementById("downloadRoomAccessHistory").addEventListener("click", function () {
form.submit();
});
</script>
This does exactly what i want and it works, but i was trying to find a more nice solution because my experience in ASP.NET MVC is low.
You're using the wrong tool for the job.
Since the Url.Action() helper runs on the server-side, it has already executed when the page was first loaded, and generated a fixed URL which is inserted into the page's HTML. It cannot know what the user later enters into the textbox.
If you want to capture data which a user has entered, it makes more sense to use a form. In this case I've used the BeginForm tag helper to generate a suitable HTML <form> tag:
<form asp-action="GetRoomAccessHistory" asp-controller="Files" method="get">
<input type="text" id="createdDate" name="createdDate" placeholder="dd/mm/yyyy" />
<input type="submit" value="Download"/>
</form>
When submitted, this will generate a GET request to the GetRoomAccessHistory action's URL, and append createdDate as a querystring variable, using the value from the textbox.
For Get request,try to use window.location.href.
<input type = "text" id="createdDate" placeholder="dd/mm/yyyy" />
<a onclick = "navigate()" >
< input type="button" value='Download' />
</a>
<script type = 'text/javascript' >
function navigate()
{
var createdDate = document.getElementById('createdDate').value;
var url = "/Files/GetRoomAccessHistory?createdDate=" + createdDate;
window.location.href = url;
}
</script>
And your solution could be simplified to
<form method = "get" asp-controller="Files" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
<input type = "text" name="createdDate" placeholder="dd/mm/yyyy" />
<button type = "button" onclick="myFunction()">Download</button>
</form>
<script>
function myFunction()
{
document.getElementById("formGetRoomAccessHistory").submit();
}
</script>

Send info to code behind without postback

First, I'm a student, though this is not for school. I'm trying to create a contact us page for my church's website (http://fpcoakwood.azurewebsites.net). I haven't published the contact page yet, as I'm trying to build it. I'm using Bootstrap/jQuery/ASP.NET to build the site. There is a videos page that uses ASP to get the list of videos from YouTube for our channel, and then populates the select html element from that, and I have it working so that selecting a different video loads that video into the player without a postback (though I do wish I could make the back button take me back to the prior page, rather than cycling through prior videos first).
On this page, my challenge is that I'm trying to send an email. I have the code behind working so that I can send the email, but I'm also trying to disable the send button and fadeIn a result div, which would show either success or failure to send the email. The problem is that because the postback occurs, the page reloads, and I lose the disabling of the button and the showing of the status.
Here's some of the code I have so far:
HTML:
<div class="form-group">
<asp:Button class="btn btn-success" ID="sendMail" OnClick="sendMail_Click" OnClientClick="sendMail(); return false;" runat="server" UseSubmitBehavior="false" Text="Send Message" />
</div>
<div id="sendSuccess" runat="server">Success!</div>
<div id="sendFailed" runat="server">Unable to send message. Please try again later.</div>
JS:
$("#sendMail").click(function (event) {
event.preventDefault();
$("#sendSuccess").fadeOut();
$("#sendFailed").fadeOut();
$("#sendMail").attr("disabled", true);
$("#sendMail").attr("text", "Sending...");
return true;
});
C#:
protected void sendMail_Click(object sender, EventArgs e)
{
//sendMail.Enabled = false;
//sendMail.Text = "Sending...";
SendMessage();
}
If I get rid of the javascript function, I can send the email. It goes through no problems. But with the javascript function, the breakpoint in the C# function is never hit, so it's not hitting the server. What I want is to be able to validate in js before sending to the server, then send to the server without a postback, and have the server send a message to the js allowing either the fail or the success message div to fadeIn().
Any help will be VERY much appreciated. Thanks in advance!
The jquery function runs before the C# code behind and interfere with it's result.
To do what you want you could do all the work on the server-side.
You can use ajax to do that.
Use an updatepanel around the controls and an updateprogress with the "sending..." message. Capture the sendmessage() result and then show the #sendsuccess or #sendFailed according to it.
I ended up using the answer in this post (How to call code behind method from a javascript function?) to do what I wanted to do. Surely it could have been done with Filipe's answer, but at this point, I'm already drinking from a fire hose trying to learn what I can learn, so this was easier for me, since I already have a fair understanding of all of the pieces involved.
Here's my HTML:
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div class="col-md-8 col-md-offset-2" runat="server">
<div class="form-group">
<label for="userName">Your name (requrired):</label>
<input type="text" class="form-control" id="userName" runat="server" />
</div>
<div class="form-group">
<label for="email">Email address (required):</label>
<input type="email" class="form-control" id="email" runat="server" />
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" id="message" rows="5" runat="server"></textarea>
</div>
<div class="form-group">
<asp:Button class="btn btn-success" ID="sendMail" runat="server" OnClientClick="sendMail(); return false;" UseSubmitBehavior="false" Text="Send Message" />
</div>
<div id="sendSuccess" runat="server">Your message has been sent. Thank you for contacting First Pentecostal Church of Oakwood. You are important to us!</div>
<div id="sendFailed" runat="server">Unable to send message. Please try again later. You are important to us!</div>
</div>
</form>
There is an error in the HTML, as the OnClientClick doesn't find the function, but without it and the return false, the page does a postback. I'm not sure how to fix it, as the preventDefault() in the JS doesn't solve it, and using the UseSubmitBehavior by itself doesn't do it, either. But this works, though it shows as an error in the developer tools in the browser.
Here's the CSS:
#sendSuccess,
#sendFailed {
display:none;
border: 1px solid black;
border-radius: 5px;
padding: 5px;
}
#sendSuccess {
background-color: rgba(147, 197, 75, .7);
}
#sendFailed {
background-color: rgba(201, 48, 44, .7);
}
Here's the JavaScript:
//Set up event handler for send message contact page button
$("#sendMail").click(function (event) {
event.preventDefault();
sendMail();
});
//above is in the $(document).ready function
function sendMail() {
$("#sendSuccess").fadeOut();
$("#sendFailed").fadeOut();
$("#sendMail").prop("value", "Sending...");
$("#sendMail").attr("disabled", true);
var name = $("#userName").val();
var email = $("#email").val();
var msg = $("#message").val();
PageMethods.SendMessage(name, email, msg, onSuccess, onError);
}
function onSuccess(result) {
if (result) {
$("#sendSuccess").fadeIn();
$("#userName").prop("value", "");
$("#email").prop("value", "");
$("#message").prop("value", "");
$("#sendMail").prop("value", "Send Message");
$("#sendMail").attr("disabled", false);
}
else { onError(result); }
}
function onError(result) {
$("#sendFailed").fadeIn();
$("#sendMail").prop("value", "Try Again");
$("#sendMail").attr("disabled", false);
}
And here's the C#:
[System.Web.Services.WebMethod()]
public static bool SendMessage(string user, string email, string msg)
{
string to = "xxxxxxxxx#outlook.com";
string from = "xxxxxxxxxx#outlook.com";
string subject = "Message from OakwoodFPC.org Contact Page";
string body = "From: " + user + "\n";
body += "Email: " + email + "\n";
body += msg;
MailMessage o = new MailMessage(from, to, subject, body);
NetworkCredential cred = new NetworkCredential("xxxxxxxxxx#outlook.com", "password");
SmtpClient smtp = new SmtpClient("smtp.live.com", 587);
smtp.EnableSsl = true;
smtp.Credentials = cred;
try
{
smtp.Send(o);
return true;
}
catch (Exception)
{
return false;
}
}

ASP.Net Modal Not Displaying

I have an ASP.Net form which on when a 'Submit' button is clicked it sends an email. This can take some time so i wanted to add a processing modal to the user knows that something is happening.
Now i have the modal displaying BUT it only displays once the email has either been sent of failed. I need this modal to be displayed as soon as the button is clicked and then close once the email action has either sent it or failed the send it.
If it fails my page do currently display an error message.
My HTML is
<div class="form-group">
<div class="col-xs-12">
<div class="pull-right">
<asp:LinkButton ID="pg3button" runat="server" OnClick="pg3button_Click" CssClass="btn btn-primary"><span aria-hidden="true" class="glyphicon glyphicon-ok"></span> Send & complete</asp:LinkButton>
</div>
</div>
</div>
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<asp:UpdatePanel ID="upModal" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">
<asp:Label ID="lblModalTitle" runat="server" Text="">Processing</asp:Label>
</h4>
</div>
<div class="modal-body">
<asp:Label ID="lblModalBody" runat="server" Text="">
<p class="text-center">IMAGE GOES HERE</p>
</asp:Label>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
My code behind for my onclick for the submit button is
protected void pg3button_Click(object sender, EventArgs e)
{
try
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
upModal.Update();
//Create the msg object to be sent
MailMessage msg = new MailMessage();
//Add your email address to the recipients
msg.To.Add("test#test.co.uk");
//Configure the address we are sending the mail from
MailAddress address = new MailAddress("test#test.co.uk");
msg.From = address;
//Append their name in the beginning of the subject
msg.Subject = "Enquiry";
msg.Body = Label1.Text + " " + Session["pg1input"].ToString()
+ Environment.NewLine.ToString() +
Label2.Text + " " + Session["pg1dd"].ToString()
+ Environment.NewLine.ToString() +
Label3.Text + " " + Session["pg2"].ToString();
//Configure an SmtpClient to send the mail.
SmtpClient client = new SmtpClient("smtp.live.com", 587);
client.EnableSsl = true; //only enable this if your provider requires it
//Setup credentials to login to our sender email address ("UserName", "Password")
NetworkCredential credentials = new NetworkCredential("test#test.co.uk", "Password10");
client.Credentials = credentials;
//MODAL CODE TO GO HERE
//Send the msg
client.Send(msg);
Response.Redirect("/Session/pg4.aspx");
}
catch
{
//If the message failed at some point, let the user know
lblResult.Text = "<div class=\"form-group\">" + "<div class=\"col-xs-12\">" + "There was a problem sending your request. Please try again." + "</div>" + "</div>" + "<div class=\"form-group\">" + "<div class=\"col-xs-12\">" + "If the error persists, please contact us." + "</div>" + "</div>";
}
}
I have also tried moving the follwing code outside my try
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
upModal.Update();
I was think if there was a way i could call my button click then a function which has my email code in it but im new to ASP.Net and webforms
All i need is for the modal to be displayed the minute the button is clicked and removed once the page either redirects (if successful) or when my error is displayed
just use JavaScript instead of server side code for modal popup
when you click on button add OnClinetClick event and use a javascript function like
<asp:button id="pg3button" runat="server" OnClick="pg3button_Click" OnClientclick="ShowPopup();"></asp:button>
<script>
function ShowPopup()
{
$('#myModal').modal();
}
<script>
also remove update panel it is not useful in this context.
You are registering your script which shows modal,using the reigisterStartupScript function. Since it is a script it will get registered on the page only after the execution of your c# code. Try moving it to the aspx page itself on the onClientClick event of the button.
$( "#buttonId" ).click(function() {
$('#myModal').modal();
});

keeping the data in a form after it has been sent

I have a form that you enter data into and it performs a calculation on it and give an answer. what i want to do is for it to keep the data in the form so that you can quickly repost so that you don't have to change all the data. but I cant keep coming up with the error of it not existing, which I suppose is correct until the form has been posted!
#{
var total = 0m;
var totalMessage = "";
if (IsPost)
{
var age = Request["frmage"].AsInt(0);
var weight = Request["frmweight"].AsDecimal();
var SerCre = Request["frmSerCre"].AsDecimal();
var sexfactor = Request["frmGender"]== "M" ? 1.23m : 1.04m;
total =Convert.ToDecimal ((((140 - age)*weight)* sexfactor )/SerCre ) ;
totalMessage = total.ToString("0.00") + "(ml/min) ";
}
}
<div class="memberRegistration">
<form method="post">
<p>
<label class="formLabel">Age:</label> in years
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
</p>
<p>
<label class="formLabel">Weight:</label> in Kg (1st = 6.35kg)
<input class="formTextField" type="text" name="frmWeight" value="#weight"/>
</p>
<p>
<label class="formLabel">Serum Creatinine:</label> in μmol/L
<input class="formTextField" type="text" name="frmSerCre" value="#SerCre"/>
</p>
<p>
<label class="fieldLabel">Gender:</label>
<select name="frmGender" id="select" value="#sexfactor">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</p>
<p><input type="submit" value="Calculate" /></p>
</form>
<p>Calculated creatinine clearance <b>#totalMessage</b></p>
</div>
Try this
var age = 0;
if (IsPost)
{
age = Request["frmage"].AsInt(0);
}
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
But normally it would be better to use a model to hold your values, then in your controller you pass those values back again to your form
Enable the ViewState of the page and controls and also use aspx control, not HTML.
I don't thing that i realy understand the Question because the default thing is that the web page keeps it's view state so the data will still be the same after the post back but here's the solution :
you can simply use ASP Controls because it keep it's view state
or you can give each control of them it's value in the C# , you can assign to each control it's value back
Hope I Helped
Since you are using ASP.NET MVC Razor, what you can do is, do not submit the form using <input type="submit" value="Calculate" /> , instead change it to a simple button like
<input type="button" value="Calculate" onclick="javascript:Submitform();" />
and submit the form using Jquery POST.e.g. like below
function SubmitForm(){
var formData = $("form").serialize() ;
var submitUrl = 'yourURL' ;
$.ajax({
type : 'POST' ,
url : submitUrl ,
data : formData ,
success : function (data ){ alert ("Request successful") ;}
error : function (jqXHR, status , errorthrown) { alert ("error Occured");}
});
}

Why is the data from my html form not submitting?

I am developing asp.net mvc application. I have a section on the form where I add some text boxes dynamically when the user clicks a "Add New Part" button. The problem is when I submit the form I don't get the data from the fields I added dynamically. I am passing the FormCollection to my controller and stepping through the code in the debugger and those fields are not there. If I look at them in firebug I see them just fine. Any ideas?
Here is the javascript for adding the text fields to the page:
function moreFields() {
var newFields = document.getElementById('readrootpu').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName;
}
var insertHere = document.getElementById('newpartusageitems');
insertHere.parentNode.insertBefore(newFields, insertHere);
}
Here is the html:
<div id="readrootpu" class="usedparts" style="display: none">
<% var fieldPrefix = "PartUsage[]."; %>
Part ID:
<%= Html.TextBox(fieldPrefix + "ID", "")%>
Serial Number:
<%= Html.TextBox(fieldPrefix + "Serial", "")%>
Quantity:
<%= Html.TextBox(fieldPrefix + "Quantity", "") %>
<input type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
When I inspect the html with firebug it looks fine to me:
Part ID: <input type="text" name="PartUsage[].ID" id="PartUsage[]_ID" value="" />
Serial Number: <input type="text" name="PartUsage[].Serial" id="PartUsage[]_Serial" value="" />
Quantity: <input type="text" name="PartUsage[].Quantity" id="PartUsage[]_Quantity" value="" />
Thoughts?
Verify with Firebug that all the post data is being sent from the page via the "Net" tab.
Also, i agree with Kobi: you need to increment the ID's on the cloned elements so they are unique.
I would suggest you look into jQuery for dynamically creating html elements. I have only just started learning jQuery and its very easy.
The following code demonstrates a simple file upload form that allows the user can add more input elements dynamically. Each time the jQuery adds a new input element, i append a chr to the id attribute so they are all unique. Hopefully this helps you:
The script block for the jQuery.. notice the last part is for the ajax animation. The actual copying code is only those 4 lines from $("#moreFiles").click
<script type="text/javascript">
var counter = "oneFile";
$(document).ready(function() {
$("#moreFiles").click(function() {
var newCounter=counter+"1";
$("p#"+counter).after("<p id='"+newCounter+"'><input type='file' name='"+newCounter+"' id='"+newCounter+"' size='60' /></p>");
counter=newCounter;
});
$("#submitUpload").click(function() {
$("#submitUpload").val("Uploading...");
$("img.uploadingGif").show();
});
});
</script>
..and the aspnet markup:
<% string postUrl = Model.PostUrl + (Model.ModelID > 0 ? "/" + Model.ModelID.ToString() : ""); %>
<form id="uploadForm" class="uploadForm" action="<% =postUrl %>"
method="post" enctype="multipart/form-data">
<label>Select file(s) for upload (size must not exceed
<% =Html.Encode(ServiceConstants.MAX_FILE_UPLOAD_SIZE_INBYTES) %> bytes):</label>
<p id="oneFile"><input type="file" name="oneFile" id="oneFile" size="60" /></p>
<% if(Model.MultipleFiles) { %>
<p><a id="moreFiles" href="#">add more files</a></p>
<input id="MultipleFiles" type="hidden" name="MultipleFiles" value="true" />
<% } %>
<p><%--<input id="submitUpload" type="submit" value="Upload" />--%>
<% =Html.InputSubmit("Upload","submitUpload") %>
<% =Html.LoadingImage("uploadingGif") %>
</form>
..this all only boils down to a few lines of html and jQuery.
When you have multiple values on fields with same names, you should be able to see them on the server side using Request.Form.GetValues("key").
You should note that when you clone the nodes, you create copies with the same IDs, which is considered invalid.
Also, you have a for loop there, and I don't quite get what it does (reads the node's name and sets it back - what is the reason for doing that? Should that be var theName = newFields[i].name ?)
I was working with plain HTML when my form worked fine if all the fields were left blank, but it would not submit if I filled out the form.
Later I realized that it was because of a text-field entry 'Email' in which I was entering an email-address containing the character '#'. When I removed the '#', the form started submitting again.
You cannot just aribtrarily add text boxes client-side without having the corresponding server-side controls ready to read the data from the postback. However, you should be able to read the raw data from HttpRequest.Form.
update: oops! it's MVC. I didn't read^H^H^H^H see that. never mind.
-Oisin

Categories

Resources