Skip to content
Permalink
Browse files

Step 3: Support for appending

  • Loading branch information
haacked committed Nov 20, 2019
1 parent 1cb9921 commit 2a043d8228bf4a66def5456aa8246db8bc4b2380
Showing with 16 additions and 6 deletions.
  1. +4 −4 src/Pages/Index.cshtml
  2. +1 −1 src/Pages/Index.cshtml.cs
  3. +11 −1 src/wwwroot/js/site.js
@@ -9,11 +9,11 @@
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<div id="the-message" class="flash">
@Model.TheMessage
</div>
<ul id="the-message" class="flash">
<li>@Model.TheMessage</li>
</ul>

<form method="post" data-update-target-selector="#the-message">
<form method="post" data-update-target-selector="#the-message" data-update-type="append">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="@Model.TheValue"></label>
@@ -38,7 +38,7 @@ public IActionResult OnPost()
if (Request.IsAjaxRequest())
{
// Typically you'd return a partial here.
return Content(TheMessage);
return Content($"<li>{TheMessage}</li>");
}

return Page();
@@ -22,6 +22,7 @@ document.querySelectorAll('form[data-update-target-selector]')
if (form.submitter) {
formData.append(form.submitter.name, form.submitter.value);
form.submitter.setAttribute('disabled', 'disabled');
form.submitter.classList.add('loading');
}
fetch(form.action, {
method: 'POST',
@@ -33,14 +34,23 @@ document.querySelectorAll('form[data-update-target-selector]')
.then(response => {
if (form.submitter) {
form.submitter.removeAttribute('disabled');
form.submitter.classList.remove('loading');
}
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
const updateType = form.dataset.updateType || 'replace';
if (updateType === 'replace') {
updateTarget.innerHTML = html
}
else /* append */ {
const div = document.createElement('div');
div.innerHTML = html;
updateTarget.appendChild(div.firstChild);
}
}
// Clear inputs
form.reset();

0 comments on commit 2a043d8

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