Skip to content
Permalink
Browse files

Step 2: Basic Update Panel

  • Loading branch information
haacked committed Nov 20, 2019
1 parent b431650 commit 1cb9921f63ab14886ef0de97f131d43aef13deba
Showing with 69 additions and 2 deletions.
  1. +3 −2 src/Pages/Index.cshtml
  2. +7 −0 src/Pages/Index.cshtml.cs
  3. +14 −0 src/Pages/RequestExtensions.cs
  4. +45 −0 src/wwwroot/js/site.js
@@ -13,12 +13,13 @@
@Model.TheMessage
</div>

<form method="post">
<form method="post" data-update-target-selector="#the-message">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="@Model.TheValue"></label>
<input asp-for="@Model.TheValue" />
<span asp-validation-for="@Model.TheValue" class="text-danger"></span>
</div>
<input type="submit" value="Submit"/>
</form>
</form>

@@ -34,6 +34,13 @@ public IActionResult OnPost()
}

TheMessage = $"Yay, you posted '{TheValue}'";

if (Request.IsAjaxRequest())
{
// Typically you'd return a partial here.
return Content(TheMessage);
}

return Page();
}
}
@@ -0,0 +1,14 @@
using Microsoft.AspNetCore.Http;

namespace MvcExplorations.Pages
{
public static class RequestExtensions
{
public const string XmlHttpRequest = nameof(XmlHttpRequest);

public static bool IsAjaxRequest(this HttpRequest request)
{
return request.Headers["X-Requested-With"] == XmlHttpRequest;
}
}
}
@@ -2,3 +2,48 @@
// for details on configuring this project to bundle and minify static web assets.

// Write your Javascript code.

// Set up ajaxified forms
document.querySelectorAll('form[data-update-target-selector]')
.forEach(form => {
const document = form.ownerDocument;

// Set up submitter property on submit button click
// This lets us include the button value in form data.
// And lets us disable the button while submitting.
form.addEventListener('click', evt => {
form.submitter = evt.target.closest('[type=submit]')
});

form.addEventListener('submit', evt => {
evt.preventDefault();

const formData = new FormData(form);
if (form.submitter) {
formData.append(form.submitter.name, form.submitter.value);
form.submitter.setAttribute('disabled', 'disabled');
}
fetch(form.action, {
method: 'POST',
headers: {
'X-Requested-With': 'XmlHttpRequest'
},
body: formData
})
.then(response => {
if (form.submitter) {
form.submitter.removeAttribute('disabled');
}
if (!response.ok) throw response;
return response.text()
}).then(html => {
const updateTarget = form.querySelector(form.dataset.updateTargetSelector)
|| document.querySelector(form.dataset.updateTargetSelector);
if (updateTarget) {
updateTarget.innerHTML = html
}
// Clear inputs
form.reset();
})
})
});

0 comments on commit 1cb9921

Please sign in to comment.
You can’t perform that action at this time.