Skip to content

Commit

Permalink
Day 9 - Ajax
Browse files Browse the repository at this point in the history
  • Loading branch information
fdeniz07 committed Sep 25, 2021
1 parent f12517c commit 5ddcf1b
Show file tree
Hide file tree
Showing 18 changed files with 400 additions and 126 deletions.
34 changes: 33 additions & 1 deletion BlogWeb/Areas/Admin/Controllers/CategoryController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
using System.Threading.Tasks;
using System.Text.Json;
using System.Threading.Tasks;
using BlogWeb.Areas.Admin.Models;
using BusinessLayer.Abstract;
using CoreLayer.Utilities.Extensions;
using CoreLayer.Utilities.Results.ComplexTypes;
using EntityLayer.Dtos;
using Microsoft.AspNetCore.Mvc;

namespace BlogWeb.Areas.Admin.Controllers
Expand All @@ -19,7 +23,35 @@ public async Task<IActionResult> Index()
{
var result = await _categoryService.GetAll();
return View(result.Data);
}

[HttpGet]
public IActionResult Add()
{
return PartialView("_CategoryAddPartial");
}

[HttpPost]
public async Task<IActionResult> Add(CategoryAddDto categoryAddDto)
{
if (ModelState.IsValid)
{
var result = await _categoryService.Add(categoryAddDto, "Fatih Deniz");
if (result.ResultStatus==ResultStatus.Success)
{
var categoryAddAjaxModel = JsonSerializer.Serialize(new CategoryAddAjaxViewModel
{
CategoryDto = result.Data,
CategoryAddPartial = await this.RenderViewToStringAsync("_CategoryAddPartial", categoryAddDto)
});
return Json(categoryAddAjaxModel);
}
}
var categoryAddAjaxErrorModel = JsonSerializer.Serialize(new CategoryAddAjaxViewModel
{
CategoryAddPartial = await this.RenderViewToStringAsync("_CategoryAddPartial", categoryAddDto)
});
return Json(categoryAddAjaxErrorModel);
}
}
}
11 changes: 11 additions & 0 deletions BlogWeb/Areas/Admin/Models/CategoryAddAjaxViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using EntityLayer.Dtos;

namespace BlogWeb.Areas.Admin.Models
{
public class CategoryAddAjaxViewModel
{
public CategoryAddDto CategoryAddDto { get; set; }
public string CategoryAddPartial { get; set; }
public CategoryDto CategoryDto { get; set; }
}
}
61 changes: 54 additions & 7 deletions BlogWeb/Areas/Admin/Views/Category/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
}
@if (Model.ResultStatus == ResultStatus.Success)
{
<div id="modalPlaceHolder" aria-hidden="true"></div>

<div class="card mb-4 mt-2">
<div class="card-header">
<i class="fas fa-table mr-1"></i>
Expand Down Expand Up @@ -527,32 +529,34 @@
@if (Model.ResultStatus == ResultStatus.Error)
{
<div class="alert alert-danger mt-3">
@Model.Message <br/>
@Model.Message <br />
Dashboard sayfasına geri dönmek için lütfen <a class="alert-link" asp-area="Admin" asp-controller="Home" asp-action="Index">tıklayınız</a>
</div>
}

@section Scripts
{
<script>
$(document).ready(function () {
$(document).ready(function() {
$('#categoriesTable').DataTable({
dom:
"<'row'<'col-sm-3'l><'col-sm-6 text-center'B><'col-sm-3'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
buttons: [
{
text: 'Ekle',
attr: {
id: "btnAdd",
},
className: 'btn btn-success',
action: function (e, dt, node, config) {
alert('Ekle butonuna basıldı.');
action: function(e, dt, node, config) {
}
},
{
text: 'Yenile',
className: 'btn btn-warning',
action: function (e, dt, node, config) {
action: function(e, dt, node, config) {
alert('Yenile butonuna basıldı.');
}
}
Expand Down Expand Up @@ -761,6 +765,49 @@
}
}
});
@* DataTables ends here *@
@* Ajax GET / Getting the _CategoryAddPartial as Modal Form starts from here. *@
$(function() {
const url = '@Url.Action("Add", "Category")';
const placeHolderDiv = $('#modalPlaceHolder');
$('#btnAdd').click(function() {
$.get(url).done(function(data) {
placeHolderDiv.html(data);
placeHolderDiv.find(".modal").modal('show');
});
});
@* Ajax GET / Getting the _CategoryAddPartial as Modal Form ends here. *@
@* Ajax POST / Posting the FormData as CategoryAddDto starts from here. *@
placeHolderDiv.on('click',
'#btnSave',
function(event) {
event.preventDefault();
const form = $('#form-category-add');
const actionUrl = form.attr('action');
const dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function(data) {
const categoryAddAjaxModel = jQuery.parseJSON(data);
const newFormBody = $('.modal-body', categoryAddAjaxModel.CategoryAddPartial);
placeHolderDiv.find('.modal-body').replaceWith(newFormBody);
const isValid = newFormBody.find('[name="IsValid"]').val() === 'True';
if (isValid) {
placeHolderDiv.find('.modal').Modal('hide');
const newTableRow = `
<td>${categoryAddAjaxModel.CategoryDto.Id}</td>
<td>${categoryAddAjaxModel.CategoryDto.CategoryName}</td>
<td>${categoryAddAjaxModel.CategoryDto.Description}</td>
<td>${categoryAddAjaxModel.CategoryDto.IsActive}</td>
<td>${categoryAddAjaxModel.CategoryDto.IsDeleted}</td>
<td>${categoryAddAjaxModel.CategoryDto.Note}</td>
<td>${categoryAddAjaxModel.CategoryDto.CreatedDate.ToShortDateString()}</td>
<td>${categoryAddAjaxModel.CategoryDto.CreatedByName}</td>
<td>${categoryAddAjaxModel.CategoryDto.ModifiedDate.ToShortDateString()}</td>
<td>${categoryAddAjaxModel.CategoryDto.ModifiedByName}</td>`
}
});
});
});
});
</script>
}
44 changes: 44 additions & 0 deletions BlogWeb/Areas/Admin/Views/Category/_CategoryAddPartial.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
@model EntityLayer.Dtos.CategoryAddDto

<div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><span class="fas fa-plus"></span> Kategori Ekle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="İptal">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form asp-action="Add" id="form-category-add">
<input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" />
<div asp-validation-summary="All" class="text-danger" id="validation-summary" aria-hidden="true" style="display: none"></div>
<div class="form-group">
<label asp-for="CategoryName"></label>
<input class="form-control" asp-for="CategoryName" />
<span class="text-danger" asp-validation-for="CategoryName"></span>
</div>
<div class="form-group">
<label asp-for="Description"></label>
<input class="form-control" asp-for="Description" />
<span class="text-danger" asp-validation-for="Description"></span>
</div>
<div class="form-group">
<label asp-for="Note"></label>
<input class="form-control" asp-for="Note" />
<span class="text-danger" asp-validation-for="Note"></span>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" asp-for="IsActive" />
<label asp-for="IsActive" class="form-check-label"></label>
<span class="text-danger" asp-validation-for="IsActive"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-block" data-dismiss="modal"><span class="fas fa-times"></span> İptal</button>
<button type="button" class="btn btn-primary btn-block" id="btnSave"><span class="fas fa-save" ></span> Kaydet</button>
</div>
</div>
</div>
</div>
3 changes: 3 additions & 0 deletions BlogWeb/Areas/Admin/Views/Shared/_LayoutCssPartial.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@
<link href="https://cdn.datatables.net/1.11.2/css/dataTables.bootstrap4.min.css" rel="stylesheet" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js" crossorigin="anonymous"></script>
<link href="https://cdn.datatables.net/buttons/2.0.0/css/buttons.bootstrap4.min.css" rel="stylesheet" crossorigin="anonymous" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet" crossorigin="anonymous" />



2 changes: 1 addition & 1 deletion BlogWeb/Areas/Admin/Views/Shared/_LayoutJsPartial.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@
<script src="~/assets/demo/datatables-demo.js"></script>
<script src="https://cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/buttons/2.0.0/js/buttons.bootstrap4.min.js" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" crossorigin="anonymous"></script>
4 changes: 0 additions & 4 deletions BlogWeb/BlogWeb.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@
<ProjectReference Include="..\BusinessLayer\BusinessLayer.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="Areas\Admin\Models\" />
</ItemGroup>

<ItemGroup>
<None Include="wwwroot\js\site.js" />
</ItemGroup>
Expand Down
10 changes: 8 additions & 2 deletions BlogWeb/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Text.Json.Serialization;
using BusinessLayer.AutoMapper.Profiles;
using BusinessLayer.Extensions;
using Microsoft.AspNetCore.Builder;
Expand Down Expand Up @@ -26,8 +27,13 @@ public void ConfigureServices(IServiceCollection services)
* 2-Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
*/

services.AddControllersWithViews().AddRazorRuntimeCompilation();//Bu sayede backend de yapilan degisiklerde tekrar tekrar uygulamayi derlememize ihtiyac kalmiyor. Yani frontend deki gibi kaydettikten sonra uygulamadaki degisiklikleri görebiliriz.
services.AddAutoMapper(typeof(CategoryProfile),typeof(BlogProfile)); //Derlenme sirasinda Automapper in buradaki siniflari taramasi saglaniyor.
services.AddControllersWithViews().AddRazorRuntimeCompilation().AddJsonOptions(opt =>
{
opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
opt.JsonSerializerOptions.ReferenceHandler=ReferenceHandler.Preserve;
});//Bu sayede backend de yapilan degisiklerde tekrar tekrar uygulamayi derlememize ihtiyac kalmiyor. Yani frontend deki gibi kaydettikten sonra uygulamadaki degisiklikleri görebiliriz.

services.AddAutoMapper(typeof(CategoryProfile), typeof(BlogProfile)); //Derlenme sirasinda Automapper in buradaki siniflari taramasi saglaniyor.
services.LoadMyServices(); // Daha önceden kurdugumuz yapiyi buradan yüklüyoruz
}

Expand Down
7 changes: 4 additions & 3 deletions BusinessLayer/Abstract/ICategoryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ public interface ICategoryService
Task<IDataResult<CategoryListDto>> GetAll();
Task<IDataResult<CategoryListDto>> GetAllByNonDeleted();
Task<IDataResult<CategoryListDto>> GetAllByNonDeletedAndActive();
Task<IResult> Add(CategoryAddDto categoryAddDto,string createdByName);
Task<IResult> Update(CategoryUpdateDto categoryUpdateDto, string modifiedByName);
Task<IResult> Delete(int categoryId,string modifiedByName);
Task<IDataResult<CategoryDto>> Add(CategoryAddDto categoryAddDto, string createdByName);
Task<IDataResult<CategoryDto>> Update(CategoryUpdateDto categoryUpdateDto, string modifiedByName);
Task<IResult> Delete(int categoryId, string modifiedByName);
Task<IResult> HardDelete(int categoryId);

}
}
43 changes: 28 additions & 15 deletions BusinessLayer/Concrete/CategoryManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@ public async Task<IDataResult<CategoryDto>> Get(int categoryId)
});
}

return new DataResult<CategoryDto>(ResultStatus.Error, "Böyle bir kategori bulunamadı.", null);
return new DataResult<CategoryDto>(ResultStatus.Error, "Böyle bir kategori bulunamadı.", new CategoryDto
{
Category = null,
ResultStatus = ResultStatus.Error,
Message = "Böyle bir kategori bulunamadı."
});
}

public async Task<IDataResult<CategoryListDto>> GetAll()
Expand Down Expand Up @@ -93,7 +98,7 @@ public async Task<IDataResult<CategoryListDto>> GetAllByNonDeletedAndActive()
return new DataResult<CategoryListDto>(ResultStatus.Error, "Hiç bir kategori bulunamadı.", null);
}

public async Task<IResult> Add(CategoryAddDto categoryAddDto, string createdByName)
public async Task<IDataResult<CategoryDto>> Add(CategoryAddDto categoryAddDto, string createdByName)
{
//Befor using Automapper

Expand All @@ -118,15 +123,20 @@ public async Task<IResult> Add(CategoryAddDto categoryAddDto, string createdByNa
var category = _mapper.Map<Category>(categoryAddDto);
category.CreatedByName = createdByName;
category.ModifiedByName = createdByName;
await _unitOfWork.Categories.AddAsync(category);
var addedCategory = await _unitOfWork.Categories.AddAsync(category);
await _unitOfWork.SaveAsync();

return new Result(ResultStatus.Success,
$"{categoryAddDto.CategoryName} adlı kategori başarıyla eklenmiştir");
return new DataResult<CategoryDto>(ResultStatus.Success,
$"{categoryAddDto.CategoryName} adlı kategori başarıyla eklenmiştir", new CategoryDto
{
Category = addedCategory,
ResultStatus = ResultStatus.Success,
Message = $"{categoryAddDto.CategoryName} adlı kategori başarıyla eklenmiştir"
});

}

public async Task<IResult> Update(CategoryUpdateDto categoryUpdateDto, string modifiedByName)
public async Task<IDataResult<CategoryDto>> Update(CategoryUpdateDto categoryUpdateDto, string modifiedByName)
{
//Before using Automapper

Expand All @@ -145,26 +155,29 @@ public async Task<IResult> Update(CategoryUpdateDto categoryUpdateDto, string mo
//}

//After using Automapper

var category = _mapper.Map<Category>(categoryUpdateDto);
category.ModifiedByName = modifiedByName;
await _unitOfWork.Categories.UpdateAsync(category);

var updatedCategory = await _unitOfWork.Categories.UpdateAsync(category);
await _unitOfWork.SaveAsync();
return new Result(ResultStatus.Success, $"{categoryUpdateDto.CategoryName} adlı kategori başarıyla güncellenmiştir.");

return new Result(ResultStatus.Error, "Böyle bir kategori bulunamadı.");
return new DataResult<CategoryDto>(ResultStatus.Success, $"{categoryUpdateDto.CategoryName} adlı kategori başarıyla güncellenmiştir.", new CategoryDto
{
Category = updatedCategory,
ResultStatus = ResultStatus.Success,
Message = $"{categoryUpdateDto.CategoryName} adlı kategori başarıyla eklenmiştir"
});
}

public async Task<IResult> Delete(int categoryId,string modifiedByName)
public async Task<IResult> Delete(int categoryId, string modifiedByName)
{
var category = await _unitOfWork.Categories.GetAsync(c => c.Id == categoryId);

if (category!=null)
if (category != null)
{
category.IsDeleted = true;
category.ModifiedByName = modifiedByName;
category.ModifiedDate=DateTime.Now;
category.ModifiedDate = DateTime.Now;

await _unitOfWork.Categories.UpdateAsync(category);
await _unitOfWork.SaveAsync();
Expand Down
9 changes: 5 additions & 4 deletions CoreLayer/CoreLayer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.9">
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.9">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
Loading

0 comments on commit 5ddcf1b

Please sign in to comment.