Unobtrusive Ajax lib Not sending XmlHttpRequest header

Multi tool use
Multi tool use


Unobtrusive Ajax lib Not sending XmlHttpRequest header



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? Thanks





It seems to have to do, with -what- we're sending as the 'form'. When using [BindingProperty] on the property we're using to send back and forth, the ajax call seems to work....
– Sijmen Koffeman
Jun 28 at 13:33





So, the OnPost method moved to the PageModel class with no parameters
– Sijmen Koffeman
Jun 28 at 13:41




1 Answer
1



Maybe this does explain exactly as of 'why' it works or not, but if you're using razor pages (asp.net core 2+), this repo provides a working sample:
https://github.com/psijkof/RazorPagesAjax






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

NlGJTS06M1MI s 4lO
lnYzgIwbxAfrXPSDcFR2JSjf Xy02,q

Popular posts from this blog

Rothschild family

Cinema of Italy