Created
April 18, 2019 10:08
-
-
Save 16pxdesign/1da3f139ed90490062c665d90af05b25 to your computer and use it in GitHub Desktop.
Form using #partialviews and #ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@model Contact | |
<!-- Modal --> | |
<div class="modal fade" id="add-contact" tabindex="-1" role="dialog" aria-labelledby="addContactLabel" aria-hidden="true"> | |
<div class="modal-dialog" role="document"> | |
<div class="modal-content"> | |
<div class="modal-header"> | |
<h5 class="modal-title" id="addContactLabel">Add contact</h5> | |
<button type="button" class="close" data-dismiss="modal" aria-label="Close"> | |
<span aria-hidden="true">×</span> | |
</button> | |
</div> | |
<div class="modal-body"> | |
<form asp-action="Contact" enctype="multipart/form-data"> | |
<input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" /> | |
<div class="form-group"> | |
<label asp-for="FirstName"></label> | |
<input asp-for="FirstName" class="form-control" /> | |
<span asp-validation-for="FirstName" class="text-danger"></span> | |
</div> | |
<div class="form-group"> | |
<label asp-for="LastName"></label> | |
<input asp-for="LastName" class="form-control" /> | |
<span asp-validation-for="LastName" class="text-danger"></span> | |
</div> | |
<div class="form-group"> | |
<label asp-for="Email"></label> | |
<input asp-for="Email" class="form-control" /> | |
<span asp-validation-for="Email" class="text-danger"></span> | |
</div> | |
<div class="form-group"> | |
<label asp-for="Picture"></label> | |
<input asp-for="Picture" class="form-control" /> | |
<span asp-validation-for="Picture" class="text-danger"></span> | |
</div> | |
</form> | |
</div> | |
<div class="modal-footer"> | |
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> | |
<button type="button" class="btn btn-primary" data-save="modal">Save</button> | |
</div> | |
</div> | |
</div> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@model IEnumerable<string> | |
@foreach (var notification in Model) | |
{ | |
<div class="alert alert-primary" role="alert"> | |
@notification | |
<button type="button" class="close" data-dismiss="alert" aria-label="Close"> | |
<span aria-hidden="true">×</span> | |
</button> | |
</div> | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@model IEnumerable<Contact> | |
<table id="contacts" class="table mt-5" data-url="@Url.Action("Index")"> | |
<thead> | |
<tr> | |
<th>Name</th> | |
<th>Email</th> | |
</tr> | |
</thead> | |
<tbody> | |
@foreach (var contact in Model) | |
{ | |
<tr> | |
<td>@contact.FirstName @contact.LastName</td> | |
<td>@contact.Email</td> | |
</tr> | |
} | |
</tbody> | |
</table> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Application.Models; | |
using Microsoft.AspNetCore.Mvc; | |
namespace Application.Controllers | |
{ | |
public class HomeController : Controller | |
{ | |
private readonly static List<Contact> Contacts = new List<Contact>(); | |
public IActionResult Index() | |
{ | |
var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest"; | |
if (isAjax) | |
{ | |
return PartialView("_Table", Contacts); | |
} | |
return View(Contacts); | |
} | |
public IActionResult Contact() | |
{ | |
var model = new Contact { }; | |
return PartialView("_ContactModalPartial", model); | |
} | |
[HttpPost] | |
public IActionResult Contact(Contact model) | |
{ | |
if (ModelState.IsValid) | |
{ | |
Contacts.Add(model); | |
CreateNotification("Contact saved!"); | |
} | |
return PartialView("_ContactModalPartial", model); | |
} | |
[NonAction] | |
private void CreateNotification(string message) | |
{ | |
TempData.TryGetValue("Notifications", out object value); | |
var notifications = value as List<string> ?? new List<string>(); | |
notifications.Add(message); | |
TempData["Notifications"] = notifications; | |
} | |
public IActionResult Notifications() | |
{ | |
TempData.TryGetValue("Notifications", out object value); | |
var notifications = value as IEnumerable<string> ?? Enumerable.Empty<string>(); | |
return PartialView("_NotificationsPartial", notifications); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@model IEnumerable<Contact> | |
@{ ViewData["Title"] = "Contact form"; } | |
<!-- Modal placeholder --> | |
<div id="modal-placeholder"></div> | |
<!-- Button trigger modal --> | |
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#add-contact" data-url="@Url.Action("Contact")"> | |
Add contact | |
</button> | |
<!-- Contacts table --> | |
@await Html.PartialAsync("_Table", Model) | |
<div id="notification" data-url="@Url.Action("Notifications", "Home")"></div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
var placeholderElement = $('#modal-placeholder'); | |
$(document).on('click', 'button[data-toggle="ajax-modal"]', function (event) { | |
var url = $(this).data('url'); | |
$.get(url).done(function (data) { | |
placeholderElement.html(data); | |
placeholderElement.find('.modal').modal('show'); | |
}); | |
}); | |
placeholderElement.on('click', '[data-save="modal"]', function (event) { | |
event.preventDefault(); | |
var form = $(this).parents('.modal').find('form'); | |
var actionUrl = form.attr('action'); | |
var dataToSend = new FormData(form.get(0)); | |
$.ajax({ url: actionUrl, method: 'post', data: dataToSend, processData: false, contentType: false }).done(function (data) { | |
var newBody = $('.modal-body', data); | |
placeholderElement.find('.modal-body').replaceWith(newBody); | |
var isValid = newBody.find('[name="IsValid"]').val() === 'True'; | |
if (isValid) { | |
var notificationsPlaceholder = $('#notification'); | |
var notificationsUrl = notificationsPlaceholder.data('url'); | |
$.get(notificationsUrl).done(function (notifications) { | |
notificationsPlaceholder.html(notifications); | |
}); | |
var tableElement = $('#contacts'); | |
var tableUrl = tableElement.data('url'); | |
$.get(tableUrl).done(function (table) { | |
tableElement.replaceWith(table); | |
}); | |
placeholderElement.find('.modal').modal('hide'); | |
} | |
}); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Application.Data.Models; | |
using Application.Repo; | |
using Application.Repo.Contracts; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace Application | |
{ | |
public class Startup | |
{ | |
public Startup(IConfiguration configuration) | |
{ | |
Configuration = configuration; | |
} | |
public IConfiguration Configuration { get; } | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
/* commented because not show notification | |
services.Configure<CookiePolicyOptions>(options => | |
{ | |
// This lambda determines whether user consent for non-essential cookies is needed for a given request. | |
options.CheckConsentNeeded = context => true; | |
options.MinimumSameSitePolicy = SameSiteMode.None; | |
}); | |
*/ | |
services.AddDbContext<DatabaseModel>(); | |
services.AddScoped(typeof(IUnitOfWork), typeof(UnitOfWork)); | |
services.AddScoped(typeof(IRepository<>), typeof(GenericRepository<>)); | |
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
} | |
else | |
{ | |
app.UseExceptionHandler("/Home/Error"); | |
} | |
app.UseStaticFiles(); | |
app.UseCookiePolicy(); | |
app.UseMvc(routes => | |
{ | |
routes.MapRoute( | |
name: "default", | |
template: "{controller=Home}/{action=Index}/{id?}"); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment