Add Delete details in Master Detail model - ASP.NET Core - asp.net-core

I am doing CRUD operations on a Master Detail models Team and TeamMember using modal popup. I followed this video to create Add and Delete buttons in Create action like this:
This is the code i used to perform this:
TeamController:
public IActionResult Create()
{
Team team = new Team();
team.TeamMembers.Add(new TeamMember() { TeamMemberId = 1 });
return PartialView("_AddTeamPartialView", team);
}
[HttpPost]
public IActionResult Create(Team team)
{
if (team != null)
{
_dbcontext.Team.Add(team);
_dbcontext.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
_AddTeamPartialView.cshtml:
#model Team
#{
ViewData["Title"] = "_AddTeamPartialView";
}
<div class="modal fade" role="dialog" tabindex="-1" id="addTeam" aria-labelledby="addTeamLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false" >
<div class="modal-dialog modal-xl modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h3>Team</h3>
</div>
<div class="modal-body">
<form asp-action="Create" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="TeamName" class="control-label">TeamName</label>
<input asp-for="TeamName" class="form-control" />
<span asp-validation-for="TeamName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Coach" class="control-label">Coach</label>
<input asp-for="Coach" class="form-control" />
<span asp-validation-for="Coach" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="NumberTeamMembers" class="control-label">NumberTeamMembers</label>
<input asp-for="NumberTeamMembers" class="form-control" id="NumberOfTeamMembers" />
<span asp-validation-for="NumberTeamMembers" class="text-danger"></span>
</div>
<h3>Members</h3>
<table class="table table-bordered" id="membersTable">
<thead>
<tr>
<th>Name</th>
<th>BirthDate</th>
<th>Phone</th>
<th>
<button id="addbtnMember" type="button" class="btn btn-sm btn-secondary visible"
onclick="AddItem(this)">
Add
</button>
</th>
</tr>
</thead>
<tbody >
#for (int i = 0; i < Model.TeamMembers.Count; i++)
{
<tr>
<td>
#Html.EditorFor(x => x.TeamMembers[i].Name, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
#Html.EditorFor(x => x.TeamMembers[i].BirthDate, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
#Html.EditorFor(x => x.TeamMembers[i].Phone, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
<button id="btnremove-#i" type="button" class="btn btn-sm btn-danger"
onclick="DeleteItem(this)" >
Delete
</button>
</td>
</tr>
}
</tbody>
</table>
<input type="hidden" id="hdnLastIndex" value="0" />
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="javascript:window.location.reload()">CANCEL</button>
<button type="submit" class="btn btn-primary">SAVE</button>
</div>
</form>
</div>
</div>
</div>
</div>
#*#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}*#
<script>
function DeleteItem(btn) {
$(btn).closest('tr').remove();
document.getElementById('hdnLastIndex').value = document.getElementById('hdnLastIndex').value - 1;
}
function AddItem(btn) {
var table = document.getElementById('membersTable');
var rows = table.getElementsByTagName('tr');
var rowOuterHtml = rows[rows.length - 1].outerHTML;
var lastrowIdx = document.getElementById('hdnLastIndex').value;
var RowNumber = document.getElementById('NumberOfTeamMembers').value;
var nextrowIdx = eval(lastrowIdx) + 1;
document.getElementById('hdnLastIndex').value = nextrowIdx;
rowOuterHtml = rowOuterHtml.replaceAll('_' + lastrowIdx + '_', '_' + nextrowIdx + '_');
rowOuterHtml = rowOuterHtml.replaceAll('[' + lastrowIdx + ']', '[' + nextrowIdx + ']');
rowOuterHtml = rowOuterHtml.replaceAll('-' + lastrowIdx, '-' + nextrowIdx);
if (nextrowIdx < RowNumber) {
var newRow = table.insertRow();
newRow.innerHTML = rowOuterHtml;
}
}
</script>
By using this code i can add team members less or egal the number of team members, but the problem is that when i delete one the team members (for example the first team member) during the create operation of a new team, all the team members inserted after the deleted one won't be saved. where is the problem in this code?

Related

Too few arguments to function App\Http\Controllers\TimeUserController::save(), 1 passed in Controller

I have an error:
Too few arguments to function App\Http\Controllers\TimeUserController::save(), 1 passed in C:\xampp\htdocs\lreport\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 3 expected
I want to insert data into the TimeUser table in the database. But before the data is stored in the table, I want to check first whether the id_user has been registered or not.
I'm trying to create a controller like this:
public function save($id_user, Request $request){
$id_user = TimeUser::findOrFail($id_user);
if ($id_user == null) {
$user = Auth::user();
$id = $request->id;
$id_user = $user['id'];
$time_start = date('Y-m-d H:i:s');
$time_user['id'] = $id;
$time_user['id_user'] = $id_user;
$time_user['time_start'] = $time_start;
TimeUser::create($time_user);
return redirect()->intended('home');
} else {
$time_start = date('Y-m-d H:i:s');
$time_user['time_start'] = $time_start;
TimeUser::create($time_user);
return redirect()->intended('home');
}
return redirect()->intended('/');
}
And route in web like this:
Route::controller(TimeUserController::class)->group(function () {
Route::post('/timeuser/save', 'save');
Route::get('/timeuser/save/{$id_user}', 'save');
});
in my blade.php
<form method="POST" action="{{ url('/timeuser/save')}}">
#csrf
<div class="btn-group me-2" role="group" aria-label="First group">
<button type="submit" class="btn btn-primary">START</button>
</div>
</form>
<br>
<div class="btn-group me-2" role="group" aria-label="First group">
<button type="button" class="btn btn-success">GO TO CLASSROOM</button>
</div>
<div class="btn-group me-2" role="group" aria-label="First group">
<button type="button" class="btn btn-danger">FINISH</button>
</div>
<br>
<table>
<tr>
<td>Duration</td>
<td>:</td>
<td></td>
</tr>
<tr>
<td>Last Logout </td>
<td> :</td>
<td></td>
</tr>
</table>
</div>
What and how should I fix my controller part?

Bootstrap Modal Popup background view

I am working on a ASP.NET Core CRUD applciation using modal popup i have a master detail models Stock and Article. i used this code to display the modal popup:
StockController:
public IActionResult Index()
{
List<Category> categories = _dbcontext.Category.ToList();
ViewBag.ListCategories = new SelectList(categories, "CategoryId", "CategoryName");
List<Stock> AllStocks = _dbcontext.Stock.ToList();
return View(AllStocks);
}
[HttpGet]
public IActionResult Create()
{
Stock stock = new Stock();
stock.Articles.Add(new Article() { ArticleId = 1 });
return View("_AddStockPartialView", stock);
}
[HttpPost]
public IActionResult Create(Stock stock)
{
if (stock != null)
{
_dbcontext.Stock.Add(stock);
_dbcontext.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
Index.cshtml:
#model IEnumerable<Stock>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Theme.cshtml";
}
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Stock</h3>
<div class="card-tools">
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#addStock" onclick="GetDetails()">
<i class="fa fa-plus"></i>
Ajouter
</button>
</div>
</div>
<div class="card-body" id="display">
<table class="table table-bordered table-hover">
.....
</table>
</div>
</div>
</div>
</div>
<script>
function GetDetails() {
$.ajax({
type: "Get",
url: "/Stock/Create",
success: function (res) {
$("#display").html(res);
$("#addStock").modal('show');
}
});
}
</script>
_AddStockPartialView.cshtml:
#model GestionStock.Models.Stock
#{
ViewData["Title"] = "_AddStockPartialView";
}
<div class="modal fade " role="dialog" tabindex="-1" id="addStock" aria-labelledby="addStockLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5>Stock</h5>
</div>
<div class="modal-body">
<form asp-action="Create" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="CategoryId" class="control-label"></label>
<select asp-for="CategoryId" class="form-control" asp-items="ViewBag.ListCategories"></select>
<span asp-validation-for="CategoryId" class="text-danger"></span>
</div>
.......
<table class="table table-striped" id="articleTable">
<thead>
<tr>
<th>Numero serie</th>
<th>Marque</th>
<th>etat</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Articles.Count; i++)
{
<tr>
<td>
#Html.EditorFor(x => x.Articles[i].NumeroSerie, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
#Html.EditorFor(x => x.Articles[i].Marque, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
#Html.EditorFor(x => x.Articles[i].Etat, new { htmlAttributes = new { #class = "form-control" } })
</td>
</tr>
}
</tbody>
</table>
<input type="hidden" id="hdnLastIndex" value="0" />
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" #*onclick="javascript:window.location.reload()"*#>Annuler</button>
<button type="submit" class="btn btn-primary">Sauvegarder</button>
</div>
</form>
</div>
</div>
</div>
</div>
Everything works fine and the modal popup is displaying with master detail models. But when i click te button to display the modal popup, the background view (Index.cshtml) is changed like the picture below and the CategoryId SelectList isn't populating:
Although this is the index view which is supposed to display in the background of the modal popup:
So why is Index view chaning when displaying the modal popup?
Below is a work demo, you can refer to it.
In controller, make some change in create action.
[HttpGet]
public IActionResult Create()
{
List<Category> categories = _dbcontext.Category.ToList();
ViewBag.ListCategories = new SelectList(categories, "CategoryId", "CategoryName");
Stock stock = new Stock();
stock.Articles.Add(new Article() { ArticleId = 1 });
return PartialView("_AddStockPartialView", stock);
}
2.In the Index view:
remove table (<table>) before <div class="card-body" id="display">
3.In the _Theme.cshtml, check and make sure you already have below code:
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/GestionStock.styles.css" asp-append-version="true" />
...
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
4.result(I use my model data to show the table) :

ASP.NET Core MVC Master Detail in partial view

I am trying to do CRUD operations on a Master Detail model Department and Employee using modal popup. This is the code I used:
DepartmentController:
[HttpGet]
public IActionResult Create()
{
Department department= new Department();
department.Employees.Add(new Employee() { EmployeeId = 1 });
department.Employees.Add(new Employee() { EmployeeId = 2 });
department.Employees.Add(new Article() { EmployeeId = 3 });
return PartialView("_AddDepartmentPartialView",department);
}
[HttpPost]
public IActionResult Create(Department department)
{
if (department != null)
{
_dbcontext.Department.Add(department);
_dbcontext.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
Index.cshtml:
#model IEnumerable<Department>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Theme.cshtml";
}
<div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Department</h3>
<div class="card-tools">
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#addDepartment">
<i class="fa fa-plus"></i>
Ajouter
</button>
</div>
</div>
<div class="card-body">
.....
</div>
</div>
</div>
</div>
</div>
#await Html.PartialAsync("_AddDepartmentPartialView", new Department())
_AddDepartmentPartialView.cshtml:
#model Department
#{
ViewData["Title"] = "_AddDepartmentPartialView";
}
<div class="modal fade " role="dialog" tabindex="-1" id="addDepartment" aria-labelledby="addDepartmentLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
.....
</div>
<div class="modal-body" >
.......
<form asp-action="Create" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<table class="table">
<thead>
<tr>
<th>Employee name</th>
<th>Profession</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Employees.Count; i++)
{
<tr>
<td>
#Html.EditorFor(x => x.Employees[i].EmployeeName, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
#Html.EditorFor(x => x.Employees[i].Profession, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
#Html.EditorFor(x => x.Employees[i].Email, new { htmlAttributes = new { #class = "form-control" } })
</td>
</tr>
}
</tbody>
</table>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
<button type="submit" class="btn btn-primary" >Sauvegarder</button>
</div>
</form>
</div>
</div>
</div>
</div>
But this PartialView displays only the inputs of the Department model and it doesn't displays the rows of the table to insert employees records (it displays only the head of the table).
So, how to pass both Department and Employee to the partial view?
UPDATE
I tried the solution of #Xinran Shen, the modal popup finally appears with both models Department and Employee. But on Ajouter click, the Index view behind the modal popup changed (a table of all departments is supposed to appear but the nothing is displayed), also i have a Dropdownlist in the modal popup it appears empty and it doesn't populated. I think because i am using a custom Layout page but i couldn't find where is the problem exactly. Any help??
In Index.cshtml, You use:
#await Html.PartialAsync("_AddDepartmentPartialView", new Department())
to load the partial View, It will not create partial view by Create get method. And you just pass new Department() into partial View, The Department passed into view is null, So it doesn't display the rows of table.
You can set an onclick event on Ajouter button, When user click the button, It will access Create get method and Initialize Department with the initial value, Then return partial view to the index view.
.............
<button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#addDepartment" onclick="GetDetails()">
<i class="fa fa-plus"></i>
Ajouter
</button>
..........
<div class="card-body" id="Body">
</div>
...............
<script>
function GetDetails() {
$.ajax({
type: "Get",
url: "/Home/Create",
success: function (res) {
$("#Body").html(res);
$("#addDepartment").modal('show');
}
});
}
</script>
Then when you click button, It will show the full table.

ASP .NET core Razor page - Avoid refreshing the page

I have tow buttons in one Form, first button for add website info to a local table and second button for add social media info to another table, after all info added locally,
then I can click on 'add all info' button for add all info in same time to database.
My question is how can I add info to a table without refreshing the page?
AddAllInfo.cshtml:
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewWebSiteInfo.websiteName">Website URL</label>
<input type="text" asp-for="NewWebSiteInfo.websiteName" class="form-control" />
</div>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewWebSiteInfo.websiteUrl">Website URL</label>
<input type="text" asp-for="NewWebSiteInfo.websiteUrl" class="form-control" />
</div>
<button type="submit" validatedisable="True" asp-page-handler="AddWebsiteInfo" class="btn btn-primary" >Add Website info</button>
<div class="mb-3">
#if (AddInfoModel.WebSitelist.Count > 0)
{
<div class="col-12 border p-3">
<table class="table table-striped table-bordered">
<thead style="background-color:lightgray">
<tr>
<th>WebsiteName</th>
<th>websiteURL</th>
</tr>
</thead>
<tbody>
#foreach (Website item in AddAllInfoModel.WebSitelist)
{
<tr>
<td>#item.WebsiteName</td>
<td>#item.websiteURL</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
</br>
</br>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewSocialMediaInfo.SocialMediaName">Social Media</label>
<input type="text" asp-for="NewSocialMediaInfo.SocialMediaName" class="form-control" />
</div>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewSocialMediaInfo.SocialMediaAccount">Account</label>
<input type="text" asp-for="NewSocialMediaInfo.SocialMediaAccount" class="form-control" />
</div>
<button type="submit" validatedisable="True" asp-page-handler="AddSocialMediaInfo" class="btn btn-primary" >Add socil Media info</button>
<div class="mb-3">
#if (AddInfoModel.SocialMedialist.Count > 0)
{
<div class="col-12 border p-3">
<table class="table table-striped table-bordered">
<thead style="background-color:lightgray">
<tr>
<th>SocialMediaName</th>
<th>SocialMediaAccount</th>
</tr>
</thead>
<tbody>
#foreach (SocialMedia item in AddAllInfoModel.SocialMedialist)
{
<tr>
<td>#item.SocialMediaName</td>
<td>#item.SocialMediaAccount</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
</br>
<div class="col-4 offset-2">
<button type="submit" class="btn btn-primary form-control"> Add all info </button>
</div>
</form> ```
AddAllInfo.cshtml.cs:
public void OnPostAddSocialMediaInfo()
{
SocialMedialist.Add(new SocialMedia { SocialMediaName = NewSocialMediaInfo.SocialMediaName,
SocialMediaAccount=NewSocialMediaInfo.SocialMediaAccount});
}
public void OnPostAddWebsiteInfo()
{
WebSitelist.Add(new WebSite { WebSiteName = NewWebSiteInfo.WebsiteName,
websiteUrl =NewWebSiteInfo.websiteUrl});
}
You can use js to pass data to handler,and then use js to add html to tbody,here is a demo to add data to table without refresh the page:
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewWebSiteInfo.websiteName">Website URL</label>
<input type="text" asp-for="NewWebSiteInfo.websiteName" class="form-control" />
</div>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewWebSiteInfo.websiteUrl">Website URL</label>
<input type="text" asp-for="NewWebSiteInfo.websiteUrl" class="form-control" />
</div>
<input type="button" onclick="AddWebsiteInfo()" class="btn btn-primary" value="Add Website info">
<div class="mb-3">
#if (AddInfoModel.WebSitelist.Count > 0)
{
<div class="col-12 border p-3">
<table class="table table-striped table-bordered">
<thead style="background-color:lightgray">
<tr>
<th>WebsiteName</th>
<th>websiteURL</th>
</tr>
</thead>
<tbody>
#foreach (Website item in AddAllInfoModel.WebSitelist)
{
<tr>
<td>#item.WebsiteName</td>
<td>#item.websiteURL</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
</br>
</br>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewSocialMediaInfo.SocialMediaName">Social Media</label>
<input type="text" asp-for="NewSocialMediaInfo.SocialMediaName" class="form-control" />
</div>
<div class="col-md-6 mb-3">
<label class="form-label" asp-for="NewSocialMediaInfo.SocialMediaAccount">Account</label>
<input type="text" asp-for="NewSocialMediaInfo.SocialMediaAccount" class="form-control" />
</div>
<input type="button" onclick="AddSocialMediaInfo()" class="btn btn-primary" value="Add socil Media info">
<div class="mb-3">
#if (AddInfoModel.SocialMedialist.Count > 0)
{
<div class="col-12 border p-3">
<table class="table table-striped table-bordered">
<thead style="background-color:lightgray">
<tr>
<th>SocialMediaName</th>
<th>SocialMediaAccount</th>
</tr>
</thead>
<tbody>
#foreach (SocialMedia item in AddAllInfoModel.SocialMedialist)
{
<tr>
<td>#item.SocialMediaName</td>
<td>#item.SocialMediaAccount</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
</br>
<div class="col-4 offset-2">
<input type="button" onclick="AddAllInfo()" class="btn btn-primary" value="Add all info">
</div>
</form> ```
js:
#section Scripts{
<script>
function AddWebsiteInfo() {
var NewWebSiteInfo = {
'websiteName': $("#NewWebSiteInfo_websiteName").val(),
'websiteUrl': $("#NewWebSiteInfo_websiteUrl").val()
};
$.ajax({
type: 'POST',
url: '?handler=AddWebsiteInfo',
data: NewWebSiteInfo,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
dataType: 'json',
success: function (data) {
var html = "<tr><td>" + data.websiteName + "</td><td>" + data.websiteUrl + "</td></tr>";
$("tbody")[0].innerHTML = $("tbody")[0].innerHTML + html;
}
});
}
function AddSocialMediaInfo() {
var NewAddSocialMediaInfo = {
'SocialMediaName': $("#NewSocialMediaInfo_SocialMediaName").val(),
'SocialMediaAccount': $("#NewSocialMediaInfo_SocialMediaAccount").val()
};
$.ajax({
type: 'POST',
url: '?handler=AddSocialMediaInfo',
data: NewAddSocialMediaInfo,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
dataType: 'json',
success: function (data) {
var html = "<tr><td>" + data.socialMediaName + "</td><td>" + data.socialMediaAccount + "</td></tr>";
$("tbody")[1].innerHTML = $("tbody")[1].innerHTML + html;
}
});
}
function AddAllInfo() {
AddWebsiteInfo();
AddSocialMediaInfo();
}
</script>
}
handler:
[BindProperty]
public WebSiteInfo NewWebSiteInfo { get; set; }
[BindProperty]
public SocialMediaInfo NewSocialMediaInfo { get; set; }
public void OnGet()
{
}
public JsonResult OnPostAddWebsiteInfo()
{
WebSitelist.Add(new WebSite { WebSiteName = NewWebSiteInfo.WebsiteName,
websiteUrl =NewWebSiteInfo.websiteUrl});
return new JsonResult(NewWebSiteInfo);
}
public JsonResult OnPostAddSocialMediaInfo()
{
SocialMedialist.Add(new SocialMedia { SocialMediaName = NewSocialMediaInfo.SocialMediaName,
SocialMediaAccount=NewSocialMediaInfo.SocialMediaAccount});
return new JsonResult(NewSocialMediaInfo);
}
The best way to do this is to run the post request in javascript, this will not refresh the page.
2nd option is by calling the get method again at the end of the post method and then passing the model with the data to the get. So that when the page refreshes the data is filled in again

ASP.net Core MVC - DateTime Variable Doesn't Display Expected Value

I am working on a website where I need to set the ApplicationStartDate & ApplicationEndDate. When I perform this operation, ApplicationStartDate displays correctly but ApplicationEndDate displays the value of previous record which should not be the case.
Here is the .cshtml file :
#model Derawala.Models.ViewModels.ParentForApply
#{
ViewData["Title"] = "Set Application Period";
Layout = "_Layout";
}
<h1 class="text-success mt-3"><i class="fas fa-calendar-week"></i> Set Date Range For Scholarship Acceptance :</h1>
<hr class="mx-n3" />
#if (ViewBag.IsDurationSet)
{
<div class="alert alert-success alert-dismissible fade show" role="alert">
<strong><i class="fas fa-check-circle"></i> Success!</strong> Application Acceptance Is Set From <b>#WC.AppStartDate.ToString("MMMM dd yyyy")</b> To <b>#WC.AppEndDate.ToString("MMMM dd yyyy")</b>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
}
#if (WC.AppStartDate == DateTime.MinValue || WC.AppEndDate == DateTime.MinValue)
{
<form method="post">
<div class="row">
<div class="col-md-2">
<h4 class="text-primary p-2"><i class="fas fa-hand-point-right"></i> Start Date :</h4>
</div>
<div class="col-md-4">
<input type="date" asp-for="#Model.AppPeriod.AppStartDate" class="form-control form-control-lg" required />
</div>
<div class="text-primary col-md-2">
<h4 class="p-2"><i class="fas fa-hand-point-right"></i> End Date :</h4>
</div>
<div class="col-md-4">
<input type="date" asp-for="#Model.AppPeriod.AppEndDate" class="form-control form-control-lg" required />
</div>
</div>
<div class="row d-flex justify-content-center mt-3">
<div class="col-md-2">
<button type="submit" style="font-weight:bolder;" class="btn btn-success w-100 text-white mt-1">Set Duration <i class="fas fa-calendar-check"></i></button>
</div>
<div class="col-md-2">
<button type="reset" style="font-weight:bolder;" class="btn btn-warning w-100 mt-1">Reset Date <i class="fas fa-calendar"></i></button>
</div>
</div>
</form>
}
else
{
<h3 class="text-primary"><u>Currently Set As</u> : </h3>
<div class="row">
<div class="col-md-2">
<h4 class="text-danger p-2"><i class="fas fa-hand-point-right"></i> <u>Start</u> <u>Date</u> :</h4>
</div>
<div class="col-md-4">
<h4 class="p-2">#WC.AppStartDate.ToString("dd-MM-yyyy")</h4>
</div>
<div class="col-md-2">
<h4 class="text-danger p-2"> <i class="fas fa-hand-point-right"></i> <u>End</u> <u>Date</u> :</h4>
</div>
<div class="col-md-4">
<h4 class="p-2">#WC.AppEndDate.ToString("dd-MM-yyyy")</h4>
</div>
</div>
<br /><br />
<form method="post">
<div class="row">
<div class="col-md-2">
<h4 class="text-primary p-2"><i class="fas fa-hand-point-right"></i> Start Date :</h4>
</div>
<div class="col-md-4">
<input type="date" asp-for="#Model.AppPeriod.AppStartDate" class="form-control form-control-lg" required />
</div>
<div class="text-primary col-md-2">
<h4 class="p-2"><i class="fas fa-hand-point-right"></i> End Date :</h4>
</div>
<div class="col-md-4">
<input type="date" asp-for="#Model.AppPeriod.AppEndDate" class="form-control form-control-lg" required />
</div>
</div>
<div class="row d-flex justify-content-center mt-3">
<div class="col-md-2">
<button type="submit" style="font-weight:bolder;" class="btn btn-success w-100 text-white mt-1">Set Duration <i class="fas fa-calendar-check"></i></button>
</div>
<div class="col-md-2">
<button type="reset" style="font-weight:bolder;" class="btn btn-warning w-100 mt-1">Reset Date <i class="fas fa-calendar"></i></button>
</div>
</div>
</form>
}
[HttpGet] Controller Method :
[HttpGet]
public async Task <IActionResult> AppPeriod(bool IsSuccess=false)
{
ParentForApply ParentVM = new ParentForApply();
int count = await _db.AppDuration.CountAsync();
if (count == 0)
{
WC.AppStartDate = new DateTime();
WC.AppEndDate = new DateTime();
}
else
{
WC.AppStartDate = await _db.AppDuration.MaxAsync(i => i.AppStartDate);
WC.AppEndDate = await _db.AppDuration.MaxAsync(i => i.AppEndDate);
}
ViewBag.IsDurationSet = IsSuccess;
return View();
}
[HttpPost] Controller Method :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AppPeriod(ParentForApply ParentVM)
{
int id = await _db.AppDuration.MaxAsync(i => i.Id);
var data = await _db.AppDuration.FindAsync(id);
_db.AppDuration.Remove(data);
AppDurationPeriod app = new AppDurationPeriod()
{
AppStartDate = ParentVM.AppPeriod.AppStartDate,
AppEndDate = ParentVM.AppPeriod.AppEndDate
};
WC.AppStartDate = app.AppStartDate;
WC.AppEndDate = app.AppEndDate;
await _db.AppDuration.AddAsync(app);
await _db.SaveChangesAsync();
return RedirectToAction("AppPeriod",new { IsSuccess = true});
}
I am deleting the last inserted record and inserting new record in the table to use as the latest dates.
It can be seen in the images that, database has stored the correct values but website doesn't show the same value.
In the second line of else block of the last image, something phishy happenes when I debug the code. Second line of that else block somehow changes the value of AppEndDate from the original value to 30-06-2022
This is because when you load the page, the largest data is fetched from the database table by default, you can change the HttpGet method you use to get the data like this:
[HttpGet]
public async Task<IActionResult> AppPeriod(bool IsSuccess = false)
{
ParentForApply ParentVM = new ParentForApply();
int count = await _db.AppDuration.CountAsync();
if (count == 0)
{
WC.AppStartDate = new DateTime();
WC.AppEndDate = new DateTime();
}
else
{
int id = await _db.AppDuration.MaxAsync(i => i.Id);
var data = await _db.AppDuration.FindAsync(id);
WC.AppStartDate = data.AppStartDate;
WC.AppEndDate = data.AppEndDate;
//WC.AppStartDate = await _db.AppDuration.MaxAsync(i => i.AppStartDate);
//WC.AppEndDate = await _db.AppDuration.MaxAsync(i => i.AppEndDate);
}
ViewBag.IsDurationSet = true;
return View();
}
Test Result: