Send Email with different Forms to different Email Addresses - c#

I have 2 Forms , One for Print and One for Cloud and in each Form i have an input field ,where user should write their email address in input feild and when User Submit button for example In Print Form, it should send an email with users email address (Just inform in input feild) to Print Email address and when user submit button in Cloud Form it should send an email to Cloud Email address.
For example;. if Form = Print send value of Input field in Print Form to Print Email Addresse
if Form = Cloud send value of Input field in Cloud Form to Cloud Email Address
I can get it just work for One Form for example Print , but i dont know how get this things work for the others Forms like Cloud. Can anyone please point me in right direction! thanks :)
PrintForm HTML Markup:
<form id="PrintForm">
<input type="text" id="txtEmail" />
<input type="submit" value="Send" />
</form> <br>
CloudForm HTML Markup:
<form id="CloudForm">
<input type="text" id="txtEmail" />
<input type="submit" value="Send" />
</form>
AJAX:
<script>
$(document).ready(function () {
$("#PrintForm").submit(function (e) {
e.preventDefault();
var email = $("#txtEmail").val();
$.ajax({
type: 'POST',
url: "/xxx/AjaxMethod",
dataType: 'json',
data: {
email: email,
},
success: function (status) {
console.log('Send');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
});
});
</script><br>
Controller:
[HttpPost]
public JsonResult AjaxMethod(string email)
{
var SubjectOne = "Print";
var SendToPrint = "Print#Print.com";
var errorMessage = "";
//BookingViewModel
Booking book = new Booking {
Email = email,
};
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "smtp";
WebMail.SmtpPort = 25;
WebMail.UserName = "email#email.com";
WebMail.Password = "";
WebMail.From = "email#email.com";
WebMail.EnableSsl = true;
WebMail.SmtpUseDefaultCredentials = false;
// Send email
WebMail.Send(to: SendToPrint,
subject: SubjectOne,
body: "email: " + email + "<br>"
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
return Json(book);
}

Register a submit event on the cloud form just like you do for the print form.
$("#CloudForm").submit(function (e) {
e.preventDefault();
var email = $("#txtEmail").val();
$.ajax({
type: 'POST',
url: "/xxx/AjaxMethod",
dataType: 'json',
data: {
email: email,
},
success: function (status) {
console.log('Send');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
});
If both the CloudForm and PrintForm are on the same page, you will have to change the id of the textbox inputs so that they both have an unique ID.

Add a class to the two forms:
<form id="PrintForm" id = printFormGroup">
<form id="CloudForm" id = printFormGroup">
and then amend your AJAX to respond to the class:
$(".printFormGroup").submit(function (e) {
This will cover all forms with the same class and will return whatever the user enters.

You need to update your Controller by adding the parameter named formType,
[HttpPost]
public JsonResult AjaxMethod(string email, string formType)
{
if(formType == "print")
{
//Perform print related stuff
}
else if(formType == "cloud")
{
//Perform cloud related stuff
}
}
And updating your AJAX call with data: { email, formType: "print"} for Print form,
$.ajax({
type: 'POST',
url: "/xxx/AjaxMethod",
dataType: 'json',
data: {
email: email,
formType: "print"
},
success: function (status) {
console.log('Send');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
data: { email, formType: "cloud"} for Cloud form,
$.ajax({
type: 'POST',
url: "/xxx/AjaxMethod",
dataType: 'json',
data: {
email: email,
formType: "cloud"
},
success: function (status) {
console.log('Send');
},
error: function () {
console.log('something went wrong - debug it!');
}
});

Related

Populate DropDown List using JQuery in ASP.NET MVC (Active Directory request)

EDIT: The below code works, for anybody who would need!
This question is asked alot but couldn't find help for this specific one. I need to show a dropdown list that loads while I type in a search bar. While I type, I need to search in Active Directory for the Username that is being typed, and then it shows in the dropdown list all the options (say, it would only show results after 4 characters).
I have a simple form with one input, one button, a controller function to search user from a C# class that allows me to acces the AD. I put the JQuery script which retrieves data. The data is being correctly fetched but I cannot show it in the autocomplete. Any ideas?
The form:
<form class="form-inline" method="post" action="~/Home/SearchUserResult">
<label class="sr-only" for="inlineFormInput"> Nom et/ou Prénom </label>
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" name="searchName" id="searchName" placeholder="Nom et/ou prénom"/>
<button class="btn btn-primary" type="submit" id="searchValidate"> Rechercher </button>
</form>
My AD search function:
public List<string> SearchUserByName(string name)
{
try
{
SearchResultCollection resultCollection;
DirectoryEntry ldapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.Filter = "(anr=" + name + ")";
search.PropertiesToLoad.Add("displayName");
resultCollection = search.FindAll();
if (resultCollection.Count == 0)
{
return null;
}
else
{
foreach(SearchResult sResult in resultCollection)
{
lastName.Add(sResult.Properties["displayName"][0].ToString());
}
}
return lastName;
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
}
Here is the Controller function suggest by #caner
public ActionResult SearchUserByName(string name)
{
ADManager adManager = new ADManager();
List<string> lastName = adManager.SearchUserByName(name);
if (lastName != null)
{
ViewData["Names"] = lastName;
return Json(lastName,JsonRequestBehavior.AllowGet);
}
return null;
}
Finally here is the script I have for now, it gets the data but does not show it (in alert(data) I retrieve all the info I need):
<script>
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserByName",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "JSON",
success: function (data) {
alert(data)
response($.map(data, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
</script>
Thanks for your help
EDIT: createDirectoryEntry() is a function I made just to create connection to AD.
EDIT 2 : If you have any other ideas to do that with something else than JQuery, I'm open to everything
Try jquery autocomplete like this...
your script:
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/YourController/SearchUserByName",
type: "POST",
data: { name: $("#searchName").val() },
dataType: "JSON",
success: function (data) {
response($.map(data.lastName, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
and your controller method:
public ActionResult SearchUserByName(string name)
{
.
.
.
return Json(lastName);
}
This script works for me:
<script>
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserByName",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "JSON",
success: function (data) {
alert(data)
response($.map(data, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
</script>

Data is not sent from view (ajax) to controller (c#)

I'm new to AJAX, and I don't understand, why my data was not sent to controller.
So, on my View I have two input forms and a button:
HTML:
<input type="text" name="AddName">
<input type="text" name="AddEmail">
<button class="btn btn-mini btn-primary" type="button" name="add_btn" onclick="DbAdd()">Add</button>
I need after button "add_btn" clicked take data from these two inputs and send them to controller.
JavaScript:
<script type="text/javascript">
function DbAdd()
{
// Get some values from elements on the page:
var $form = $(this),
addedName = $form.find("input[name='AddName']").val(),
addedEmail = $form.find("input[name='AddEmail']").val();
$("#UserTable").html("<div>Please Wait...</div>");
$.ajax(
{
type: "POST",
url: "Save",
data:
{
name: addedName, email: addedEmail,
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
And this is my controller's method "Save" (I need to save data got from ajax to my DB):
[HttpPost]
public ActionResult Save(User userinfo)
{
string message = "";
using (var uc = new UserContext())
{
uc.UserList.Add(userinfo);
uc.SaveChanges();
message = "Successfully Saved!";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message };
}
else
{
ViewBag.Message = message;
return View(userinfo);
}
}
The problem is that when I put a break point to my controller's method, I don't receive data from ajax, null's only. So I add an empty record to DB.
Any suggestions?
Looks like $form.find("input[name='AddName']").val() and $form.find("input[name='AddEmail']").val() both return null. You should use $("input[name='AddName']").val() and $("input[name='AddEmail']").val() instead. Change the definition of DbAdd() to below
<script type="text/javascript">
function DbAdd()
{
// Get some values from elements on the page:
var addedName = $("input[name='AddName']").val(),
addedEmail = $("input[name='AddEmail']").val();
var user = { Name: addedName, Email: addedEmail };
$("#UserTable").html("<div>Please Wait...</div>");
$.ajax(
{
type: "POST",
url: "Save",
data: JSON.stringify({ userinfo: user }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
</script>
There is an extra comma which may be causing syntax error:
data:
{
name: addedName, email: addedEmail, //<------------ here
}
and pass data like this:
var userinfo = { name: addedName, email: addedEmail };
data: JSON.stringify(userinfo)
Also you should see : Posting JavaScript objects with Ajax and ASP.NET MVC

Can't validate Recaptcha in custom code

I have read in documentation about recaptcha, that there is possibility to test it on localhost.
My problem is that I cant validate recaptcha in own code.
I need to add recapture to Razor MVC 4 web application, that is working now.
I did it in this way.
default.cshtml
$.ajax({
type: 'post',
data: myForm.serialize(),
url: "xrm/VerifyCaptcha",
success: function (msg) {
debugger
if (msg.Success != true) {
Recaptcha.reload(); // reloads a new code
$('#alert').text('Введите текст картинки!');
} else {
var dataArray = { firstName: $('#input_firstname').val(), lastName: $('#input_lastname').val(), companyName: $('#input_companyname').val(), email: $('#input_email').val(), phone: $('#input_phone').val() };
$.ajax({
type: 'get',
url: 'xrm/register',
data: dataArray,
contentType: 'application/json',
success: function (response) {
console.log(response);
$('#alert').fadeOut("normal");
$('#form').fadeOut("normal");
$('#information').fadeIn("normal");
<div class="editor-label">
Are you a human?
</div>
<div class="editor-field">
#Microsoft.Web.Helpers.ReCaptcha.GetHtml("XXXXXXXXX", "blackglass","ru",0)
</div>
Controller
[HttpPost]
public ActionResult VerifyCaptcha()
{
var valid = Microsoft.Web.Helpers.ReCaptcha.Validate(privateKey: "XXXX");
if (valid)
{
return Json(new
{
Success = true,
Message = "YES! Success!"
}, JsonRequestBehavior.AllowGet);
}
return Json(new
{
Success = false,
Message = "Error!!!"
}, JsonRequestBehavior.AllowGet);
}
But var valid = Microsoft.Web.Helpers.ReCaptcha.Validate(privateKey: "XXXX");
I have to do it through ajax call, because captcha is a part of validation mechanism on this site.
Please help with the solution of this problem.
Thanks!!!
I have found the answer.
data: myForm.serialize(),
myForm wasn't a form element to my regret. It was just the table with the name "form".
That was not my fault but it was my headache.
Now all is nice and captcha looks good.
Thanks a lot.

Update Panel in ASP.NET MVC 3

I'm looking for a way to do a "Update Panel" in ASP.NET MVC 3. I found this link: How to make update panel in ASP.NET MVC but didn't work.
So, i did this in my view:
<div>
<input type="text" id="userName" />
<button type="button" onclick="searchUserByName()">Search</button>
</div>
<div id="usersPanel">
#{Html.RenderPartial("_UserList", Model);}
</div>
<script type="text/javascript">
function searchUserByName() {
var userName = $("#userName").val();
$.post('#Url.Action("SearchUserByName")',
{username: userName},
function (htmlPartialView) {
$("#usersPanel").html(htmlPartialView);
}
);
}
</script>
And in my controller:
public ActionResult SearchUserByName(string userName)
{
List<User> users = // code to search users by name
return PartialView("_UserList", users);
}
But i don't know if is a good (or right) way to do that, or if there is a way to do this with asp.net mvc 3. There is a better way to do this, or with asp.net mvc 3?
Just use ajax request to get the results from your action methods. It basically does the same thing as update panels in asp.net.
So something like the following.
$.ajax({
async: false,
cache: false,
type: 'POST',
url: /controller/action,
data: { id: idParam },
beforeSend: function (XMLHttpRequest) {
if (confirmMessage !== undefined) {
return confirm(confirmMessage);
}
return true;
},
success: function (data) {
// do stuff
},
error: function () {
alert('An error occured');
}
});
I would do it like that.
You might also want to take a look at client side libraries for handling bindings etc. Looks like knockoutjs will be included in MVC4
In View:
<script type="text/javascript">
var userName = $("#userName").val();
$.ajax({
url: "/<ControolerName>/SearchUserByName",
type: "POST",
data: { userName: userName},
success: function (result) {
$('#divResults').html(result);
},
error: function (ex) {
alert("Error");
}
<script>
<div id="divResults">
</div>
In controller:
public PartialViewResult SearchUserByName(string userName)
{
List<User> users = // code to search users by name
return PartialView("_users", users);
}

Client-side validation against an object in ASP.Net-MVC3?

I have ah HTML5 form with an action defined as follows:
#using (Html.BeginForm("SearchAction", "ResultsController"))
The form takes in two text fields:
<input type="text" name="txtSearchTerm" id="txtSearchTerm" class="frontPageInput" placeholder="Begin your search..." required />
<input type="text" name="txtGeoLocation" id="txtGeoLocation" class="frontPageInput" required />
The txtGeoLocation field is an autocomplete field that is fed from a cached object, fed through the controller and by a model repository class through the following jQuery code:
<script type="text/javascript" language="javascript">
$(function () {
$("#txtGeoLocation").autocomplete(txtGeoLocation, {
source: function (request, response) {
$.ajax({
url: "/home/FindLocations", type: "POST",
dataType: "json",
selectFirst: true,
autoFill: true,
mustMatch: true,
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.GeoDisplay, value: item.GeoDisplay, id: item.GeoID }
}))
}
})
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
: "Nothing selected, input was " + this.value);
document.getElementById("hidLocation").value = ui.item.id;
}
});
});
There's an alert there for debugging. When clicking on the text that drops down, this alert fires, however it does not fire if you type in the whole word and hit submit.
I would like to first, validate the text in the geo text box on the client side, to ensure that it is a value contained in the collection, of not, have the text box in red, communicate that.
Thanks.
You can use jquery remote validation using the [Remote()] attribute to validate the value is in the list. You will have to do the same check on the server side when you post back as well.

Categories