We're trying to implement a simple 'subscribe to our newsletter' form with the help of the aspnet Unobtrusive Ajax (js) library.
We noticed (using Fiddler) that there is no XmlHttpRequest header being sent to the server.
What can we do to resolve?
<form class="row no-gutters justify-content-center"
asp-controller="Home" asp-action="SubscribeNewsLetter"
data-ajax="true"
data-ajax-method="POST"
data-ajax-mode="replace-with"
data-ajax-update="#updatethis"
data-ajax-loading="#loading"
data-ajax-success="Success"
data-ajax-failure="Failure">
<div id="submitted" class="col-12 col-sm-6 col-md-5 col-lg-4 underline">
<input id="emailaddress" asp-for="@emailAddress" type="text" class="newsletter-input" placeholder="Insira o seu email">
<button class="btn btn-outline-dark newsletter-btn" type="submit"><i class="fa fa-long-arrow-right"></i></button>
</div>
</form>
Our controller:
[HttpPost]
public IActionResult SubscribeNewsLetter(string emailAddress, string returnUrl)
{
if (!ModelState.IsValid)
{
return View();
}
if (Request.IsAjaxRequest())
{
return new ViewResult() { ViewName = "SubmitNewLetterSuccess" };
}
return null;
}
The 'IsAjax' extension:
public static bool IsAjaxRequest(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (request.Headers != null)
{
return request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
return false;
}
Scripts we include in the razor page:
<partial name="_ValidationScriptsPartial"/>
<script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.js"></script>
<script>
function Success() {
// do something on success client side.
$('#emailaddress').val("");
}
function Failure() {
alert("Could not submit your email address at this moment.");
}
</script>
What are we missing?