Я работаю с ASP.Net Core 2.2 и пытаюсь отправить контактную форму, возвращая сообщение de: «success» или «error», не обновляя страницу.форма работает, но я хотел бы отправить с ajax, я пытаюсь с этим
Мой код выглядит так:
Я загружаю эти сценарии
<script src="~/lib/jquery/jquery.min.js"></script>
<script src="~/lib/jquery.validation/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
дополнительно у меня есть эта функция
(function($) {
$('.contact-form').each(function(){
$(this).validate({
submitHandler: function(form) {
var $form = $(form),
$messageSuccess = $form.find('.contact-form-success'),
$messageError = $form.find('.contact-form-error'),
$submitButton = $(this.submitButton),
$errorMessage = $form.find('.mail-error-message'),
submitButtonText = $submitButton.val();
$submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);
// Fields Data
var formData = $form.serializeArray(),
data = {};
$(formData).each(function(index, obj){
data[obj.name] = obj.value;
});
// Google Recaptcha
if( data["g-recaptcha-response"] != undefined ) {
data["g-recaptcha-response"] = $form.find('#g-recaptcha-response').val();
}
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data
}).always(function(data, textStatus, jqXHR) {
$errorMessage.empty().hide();
if (data.response == 'success') {
// Uncomment the code below to redirect for a thank you page
// self.location = 'thank-you.html';
$messageSuccess.removeClass('d-none');
$messageError.addClass('d-none');
// Reset Form
$form.find('.form-control')
.val('')
.blur()
.parent()
.removeClass('has-success')
.removeClass('has-danger')
.find('label.error')
.remove();
if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageSuccess.offset().top - 80
}, 300);
}
$form.find('.form-control').removeClass('error');
$submitButton.val( submitButtonText ).attr('disabled', false);
return;
} else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
$errorMessage.html(data.errorMessage).show();
} else {
$errorMessage.html(data.responseText).show();
}
$messageError.removeClass('d-none');
$messageSuccess.addClass('d-none');
if (($messageError.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageError.offset().top - 80
}, 300);
}
$form.find('.has-success')
.removeClass('has-success');
$submitButton.val( submitButtonText ).attr('disabled', false);
});
}
});
});
}).apply(this, [jQuery]);
Мой HTML
<form method="post" id="contactForm" class="contact-form form-style-4 form-errors-light custom-form-style-1">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group col-lg-12 ml-auto my-0">
<div class="contact-form-success alert alert-success d-none" id="contactSuccess">
Message has been sent to us.
</div>
<div class="contact-form-error alert alert-danger d-none" id="contactError">
Error sending your message.
<span class="mail-error-message text-1 d-block" id="mailErrorMessage"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<input asp-for="Contacts.Name" data-msg-required="¡Por favor ingrese su nombre!" class="form-control py-2" placeholder="Nombre completo" required />
<span asp-validation-for="Contacts.Name" class="error"></span>
</div>
<div class="form-group col-lg-6">
<input asp-for="Contacts.Phone" data-msg-required="¡El número de teléfono es requerido!" class="form-control py-2" placeholder="Teléfono" required />
<span asp-validation-for="Contacts.Phone" class="error"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<input asp-for="Contacts.Email" data-msg-required="¡Su e-mail es requerido!" class="form-control py-2" placeholder="E-mail" required />
<span asp-validation-for="Contacts.Email" class="error"></span>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<textarea asp-for="Contacts.Message" data-msg-required="¡El mensaje no puede ir en blanco!" rows="4" class="form-control" placeholder="Mensaje" required></textarea>
<span asp-validation-for="Contacts.Message" class="error"></span>
</div>
</div>
<input type="submit" value="ENVIAR" class="custom-btn-style-1 btn btn-dark font-weight-bold text-uppercase btn-px-5 py-3">
</form>
My Action Controller
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var tempMenssage = "Hola Cecilia! <br/> Nos alegra informarte que que tienes un mensaje nuevo, acontinuación tu mensaje. <br/> <b>Nombre de la persona que te contácta: </b>" + Contacts.Name + "<br/><b>Su e-mail es el siguiente:</b> " + Contacts.Email + "<br/><b>A continuación el mensaje:</b> " + Contacts.Message;
await _emailSender.SendEmailAsync(
"mi-email@gmail.com",
"Tiene un nuevo mensaje",
tempMenssage);
return RedirectToPage("/Index");
}