from contact form to sendemail MVC5 - c#

Im having some contact form and I have in a HomeController method SendMessage, also in my form I have hidden success and error div.
How to call sendmessage, but to stay on the same page?

As commented by Igor, use an ajax call to hit your controller/method.
Here is an example -
<script>
$(function () {
$('#sendMail').click(function () {
$("#sendMail").empty();
$("#sendMail").attr("disabled", true);
$("#sendMail").append('<i class="fa fa-spinner fa-spin"></i>Please wait...');
$.ajax
({
url: '#Url.Action("SendMail", "ControllerName")',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ 'name': $('#txtName').val(), 'email': $('#txtEmail').val(), 'message': $('#txtMessage').val() }),
success: function (result) {
$("#sendMail").empty();
$("#sendMail").append('Send Message');
$("#sendMail").attr("disabled", false);
},
error: function (result) {
$("#sendMail").empty();
$("#sendMail").append('Send Message');
$("#sendMail").attr("disabled", false);
}
});
})
})
</script>
In above javascript function -
When user clicks on button with text 'Send Mail' and id = sendMail, I disabled the button so the user won't click it multiple times and change the text of button to 'Please wait' and add a spinner for dramatic effect. I also send email of the user and name and message with the ajax call. On ajax success, I show a toaster with success message and remove the spinner and please wait text from the button and set 'Send Mail' text again.
I removed toaster javascript part in case you want to use other notification method. Good luck.

Related

asp-all-route-data not calling action method in Asp.Net Core MVC

I am running Asp.Net Core 3.1 application where i have one left side menu in layout which i load through partial view.
To set menu link i used the anchor tag like below:
var allRouteData = new Dictionary<string, string>
{
{ "menuid", mID.ToString() },
{ "isCalledByMenu", "true" },
{ "where", "tab" }
};
<a class="#clas" data-ajax="true" data-ajax-complete="RedirectToPage('#M.MenuUrl', '#M.MenuName',true)" data-ajax-mode="replace" data-ajax-update="#myTab" asp-action="GetSubMenu" asp-controller="Base" asp-all-route-data="#allRouteData">#M.MenuName</a>
So when page loads then HTML generate like below:
<a class="nav-link btn fuse-ripple-ready" data-ajax="true" data-ajax-complete="RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services',true)" data-ajax-mode="replace" data-ajax-update="#myTab" href="/Base/GetSubMenu?menuid=9630&isCalledByMenu=true&where=tab">Professional Services</a>
Below is action method used :
public IActionResult GetSubMenu(int menuid, bool? isCalledByMenu, string where = null)
{
return ViewComponent("SubMenu", new { menuid = menuid, isCalledByMenu = isCalledByMenu, where = where });
}
In Layout page on the top i assigned the tag helper:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
But when i click on the link it is not hitting this action method.
Update: When i click menu then first it hit the list inside javascript where i do some ajax call:
$('#myTab>li>a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
e.preventDefault();
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
In SetCurrentPageNameSession method i do ajax call to set the menu name in server side to some session before calling action method.
like below:
function SetCurrentPageNameSession(CurrentPage, IsBookMark) {
if (IsBookMark==undefined)
IsBookMark = false;
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark },
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
Then after it anchor tag call the action method.
Please suggest.
Maybe you could forget data-ajax, it also doesn't work on me and I can't find the answer about it. You could code as below and it also can request the GetSubMenu and continue to excute next logic.
<div id="myTab"></div>
<a class="nav-link btn fuse-ripple-ready"
href="#">Professional Services</a>
<script>
$('a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
//e.preventDefault();
$.ajax({
url: "/Base/GetSubMenu",
async: true,
type: "get",
datatype: "json",
data: #Json.Serialize(allRouteData),
success: function (result) {
$('#myTab').html(result)
}
});
//RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services', true);
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
</script>
Comment or Remove e.preventDefault();
Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
I found the solution for the above asked question:
The issue was when i click on menu link then i used to call first it's anchor click in javascript where i did e.preventDefault() and then used to do some ajax call to pass some value to set in session. Due to e.preventDefault() call after that it was not hitting the action method.
Since i had to pass other three data to server to set somewhere. To do that i set all three value in anchor tag data-link attribute separated with Pipe like below:
data-link="9630|true|tab|/OrgOverview/ProfessionalServices|Professional Services"
function SetCurrentPageNameSession(CurrentPage, IsBookMark, MenuID, IsCalledByMenu, Where, PageUrl, PageName) {
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark, menuID: MenuID, isCalledByMenu: IsCalledByMenu, where: Where},
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
if (PageUrl != undefined && PageUrl != '' && PageUrl != null)
RedirectToPage(PageUrl, PageName, true, false)
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Then in this ajax call success i am redirecting the page with passed page url.
But still i am wondering the same code how it was working in MVC and not in asp.net core.
That's it.

Bootstrap Modal popup not showing up first time

While I first click this #btnRequestedProviderSelect button, bootstrap modal is not showing popup. But I second click it will come why?
$("#btnRequestedProviderSelect").click(function () {
$("#hdnORProvider").val('Requested');
$.ajax({
type: "Get",
async: false,
url: settings.ProviderSearchPopupURL,
data: {
coverageID: 0,
fromPage: settings.Frompage, HPID: $('#MemberHealthPlanID').val(),
LOBID: $("#MemberLOBID").val(), IPAID: $("#MemberIPAID").val()
},
success: function (data) {
$("#divProviderSearch").html(data);
$("#divProviderSearchPopup").modal();
$('#divProviderSearchPopup').modal({
keyboard: false
});
$('#divProviderSearchPopup').modal('show');
}
});
});
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

Submit form through ajax and callback an alert

I submit a form using ajax request. The form is actually inside a modal popup. The submission works well. But I want it to show an alert that said the form is submitted and close the current modal. Here is my code:
$('#btnBookRoom').click(function() {
$.ajax({
url: "/Booking/BookRoom",
type: "POST",
data: $('#frmRoomBooking').serialize(),
datatype: "json",
sucess: function(data) {
alert('Room Booking Success');
$('#roomBookingModal').modal('hide');
}
});
});
Controller:
public ActionResult BookRoom(RoomBookingInputModel roomBooking)
{
var domain = new RoomBooking
{
GuestId = roomBooking.GuestId
};
db.RoomBookings.Add(domain);
db.SaveChanges();
return Json(domain, JsonRequestBehavior.AllowGet);
}
The alert doest shows and the modal also not hiding.
sucess isn't a valid callback in jQuery's ajax method. You need to change it to success.
Or better, use promise API to bind a success handler (as AJAX callbacks are already deprecated):
$.ajax({ ... })
.then(function() {
alert('Room Booking Success');
$('#roomBookingModal').modal('hide');
});

Prevent ajax post when back button is pressed

When the form is posted(ajax), I am navigating to other page and while pressing the back button, the form is again posted.
Is there any way to stop ajax post while clicking on back button in browser ?
I have used the below code to stop previous request, but after this back and forward button are disabled in the browser.
window.onpopstate = function (e) {}; history.pushState({}, '');
NOTE: I am getting this issue only in chrome and safari.
As this answer suggest suppose you have this ajax request
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg) {
alert("Data Saved: " + msg);
}
});
window.onpopstate = function(e) {
//kill the request
xhr.abort()
};
history.pushState({}, '');

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