Why Ajax helpers doesnt work? - asp.net

Im trying to achieve a filter search box, actually it works but it just completely reload all of my Index view instead of replacing the div content:
My controller Actions (The index action and the partial action):
public IActionResult Index()
{
var grupoModels = _grupos.GetAll("");
var listaGrupos = grupoModels
.Select(resultado => new grupoCRUDModel
{
Codigo = resultado.id,
Nombre = resultado.nombre,
NIS = resultado.nis,
FeAcceso = resultado.feacceso,
Linea = resultado.Linea
});
var model = new grupoIndexModel()
{
grupos = listaGrupos
};
return View(model);
}
public IActionResult tablePartial(string filter = "")
{
var grupoModels = _grupos.GetAll(filter);
var listaGrupos = grupoModels
.Select(resultado => new grupoCRUDModel
{
Codigo = resultado.id,
Nombre = resultado.nombre,
NIS = resultado.nis,
FeAcceso = resultado.feacceso,
Linea = resultado.Linea
});
var model = new grupoIndexModel()
{
grupos = listaGrupos
};
return PartialView("tablePartial",model);
}
My Index view with the searchbox and the target div to render my partial:
<div>
<div class="mdl-grid headeritems">
<div class="mdl-cell mdl-cell--8-col ">
<h2>LISTADO DE GRUPOS</h2>
</div>
<div class="mdl-cell mdl-cell--2-col" style="text-align:right;">
<button class="mdl-button mdl-js-button mdl-button--fab" id="btnAdd">
<a class="material-icons" asp-controller="Grupo" asp-action="Crear" data-ajax="true" data-toggle="modal" data-target="#modalGrupo">add</a>
</button>
</div>
<div class="mdl-cell mdl-cell--2-col">
<form asp-controller="Grupo" asp-action="tablePartial" data-ajax-method="GET" data-ajax-update="#pdiv" data-ajax="true" method="get">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--expandable">
<label class="mdl-button mdl-js-button mdl-button--icon" for="sbox">
<i class="material-icons">search</i>
</label>
<div class="mdl-textfield__expandable-holder">
<input class="mdl-textfield__input" type="text" id="sbox" name="filter">
<label class="mdl-textfield__label" for="sample-expandable">Expandable Input</label>
</div>
</div>
</form>
</div>
</div>
<br />
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--1-col"></div>
<div id="pdiv" class="mdl-cell mdl-cell--10-col">
#Html.Partial("tablePartial")
</div>
<div class="mdl-cell mdl-cell--1-col"></div>
</div>
My partialTable code view:
#model libraryDemo.Models.grupoIndexModel
<table class="mdl-data-table mdl-js-data-table mdl-shadow--2dp" id="tablaGrupos" style="width:100%;">
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric">Nombre</th>
<th class="text-center">Linea</th>
<th class="text-center">Codigo</th>
<th colspan="2" class="text-center">Acciones</th>
</tr>
</thead>
<tbody>
#foreach (var grupo in Model.grupos)
{
<tr class="mtoRow">
<td class="mdl-data-table__cell--non-numeric">#grupo.Nombre</td>
<td class="text-center">#grupo.Linea.nombre</td>
<td class="text-center">#grupo.Codigo</td>
<td class="text-center" data-toggle="tooltip" data-placement="top" title="Editar"><a class="btn btn-warning" asp-controller="Grupo" asp-action="Editar" asp-route-id="#grupo.Codigo" data-ajax="true" data-toggle="modal" data-target="#modalGrupo">Editar</a></td>
<td class="text-center" data-toggle="tooltip" data-placement="top" title="Eliminar"><a class="btn btn-danger" asp-controller="Grupo" asp-action="Eliminar" asp-route-id="#grupo.Codigo" data-ajax="true" data-toggle="modal" data-target="#modalGrupo">Eliminar</a></td>
</tr>
}
</tbody>
</table>
Finally, my ajax function for keyup event:
$("#sbox").keyup(function () {
$("form").submit();
});

try data-ajax-url in place of asp-action
<form data-ajax-url="#Url.Action("tablePartial","Grupo")" data-ajax-method="GET" data-ajax-update="#pdiv" data-ajax="true" method="get">

Related

X.PagedList .NET Core First Page always selected in #Html.PagedListPager

I have created pagination for .Net Core 3 project using X.PagedList nuget, when I click on page number it call action that retrieve partial view and update div for data list, all ok but when I click on page number 2 the data in list updated but current page selection is still on 1, it should changed to 2. and every time click on page greater that 1 the selection remain on 1 in PagedListPager.
#Html.PagedListPager(Model.OrderViewModels, page => Url.Action("OrdersSearch2", "Orders",
new { ViewBag.SearchName, page = page }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions
{
LiElementClasses = new string[] { "page-item" },
PageClasses = new string[] { "page-link" },
}
, new AjaxOptions()
{
HttpMethod = "POST",
UpdateTargetId = "OrdersList",
}))
OrdersIndexViewModel
public class OrdersIndexViewModel
{
public IPagedList<OrderViewModel> OrderViewModels { get; set; }
public SearchOrderViewModel SearchOrderViewModel { get; set; }
}
And my Action in Orders controller
public ActionResult OrdersSearch2(int? page)
{
if (!ModelState.IsValid)
{
return View(mymodel);
}
OrderSearch ors = new OrderSearch();
ors.PageNumber = page ?? 1;
var entitiesList = orderService.FindBy(ors).ToPagedList(ors.PageNumber, 5);
var model = new OrdersIndexViewModel();
model.OrderViewModels = entitiesList.ToViewModels();
return PartialView("_OrdersListPartial", model.OrderViewModels);
}
Index.cshtml
#model OrdersIndexViewModel
<div id="OrdersList">
<partial name="_OrdersListPartial.cshtml" model="Model.OrderViewModels" />
</div>
_OrdersListPartial.cshtml
#model X.PagedList.IPagedList<OrderViewModel>
#{
int rowNo = 0;
}
<div id="basic-examples">
<div class="card">
<div class="card-content">
<div class="card-body">
<div class="row">
<div class="col-12">
<input type="submit" value="New Order" class="btn btn-primary mr-1 mb-1 waves-effect waves-light" onclick="location.href='#Url.Action("AddOrder", "Orders")'" />
</div>
</div>
<div class="" id="OrdersList">
#if (Model == null || Model.Count == 0)
{
<div class="alert alert-warning">No Orders</div>
}
else
{
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h4 class="mb-0">Orders List</h4>
</div>
<div class="card-content">
<div class="table-responsive mt-1">
<table class="table table-hover-animation mb-0">
<thead>
<tr>
<th>#</th>
<th>ID</th>
<th>CUSTOMER NAME</th>
<th>CREATED</th>
<th>DELIVERY DATE</th>
<th>STATUS</th>
<th>OPERATORS</th>
<th></th>
<th style="display:none"></th>
</tr>
</thead>
<tbody>
#foreach (var i in #Model)
{
rowNo = rowNo + 1;
<tr>
<td>#rowNo</td>
<td>#ViewBag.OrdersPrefix #i.ID</td>
<td><i class="fa fa-circle font-small-3 text-success mr-50"></i>#i.CustomerName</td>
<td>#Html.DisplayFor(x => i.CreatedDate)</td>
<td>#Html.DisplayFor(x => i.DeliveryDate)</td>
<td>#i.OrderStatusText</td>
<td class="p-1">
<ul class="list-unstyled users-list m-0 d-flex align-items-center">
<li data-toggle="tooltip" data-popup="tooltip-custom" data-placement="bottom" data-original-title="Vinnie Mostowy" class="avatar pull-up">
<img class="media-object rounded-circle" src="../../../app-assets/images/portrait/small/avatar-s-5.jpg" alt="Avatar" height="30" width="30">
</li>
<li data-toggle="tooltip" data-popup="tooltip-custom" data-placement="bottom" data-original-title="Elicia Rieske" class="avatar pull-up">
<img class="media-object rounded-circle" src="../../../app-assets/images/portrait/small/avatar-s-7.jpg" alt="Avatar" height="30" width="30">
</li>
<li data-toggle="tooltip" data-popup="tooltip-custom" data-placement="bottom" data-original-title="Julee Rossignol" class="avatar pull-up">
<img class="media-object rounded-circle" src="../../../app-assets/images/portrait/small/avatar-s-10.jpg" alt="Avatar" height="30" width="30">
</li>
<li data-toggle="tooltip" data-popup="tooltip-custom" data-placement="bottom" data-original-title="Darcey Nooner" class="avatar pull-up">
<img class="media-object rounded-circle" src="../../../app-assets/images/portrait/small/avatar-s-8.jpg" alt="Avatar" height="30" width="30">
</li>
</ul>
</td>
<td>
#Html.ActionLink("Edit", "EditOrder", "Orders", routeValues: new { ID = i.ID })
</td>
<td style="display:none">
<i class="feather icon-trash"></i>
#Html.ActionLink("Delete", "DeleteOrderDetailTempItem", "Orders", routeValues: new { ID = i.ID }, htmlAttributes: new
{
#data_ajax = "true",
#data_ajax_method = "Get",
#data_ajax_update = "#OrderDetailList",
#data_ajax_failure = "onFailureDefault",
#data_ajax_success = "ViewOnSuccess",
})
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
</div>

Dropdown PageSize selection in ASP.NET Core with PagedList problem

I am trying to add a dropdown select for PageSize in my Asp.net Core project but I am facing a problem. I followed Microsoft tutorial for pagination and I managed to to add Next and Previous button. It also keeps the page=2 and the filter I enter , but when i select PageSize to display 20 table rows (other than standar 10) resets all the filters and the current pagination. I need some help on how to add a PageSize selection the proper way so it can displays also filters and page.
Controller :
public class AppUsersController : Controller
{
private readonly PushNotificationContext _context;
public AppUsersController(PushNotificationContext context)
{
_context = context;
}
// GET: AppUsers
public async Task<IActionResult> Index(String currentId, string searchId,
String currentTotalCalls, string searchTotalCalls,
string currentLastCall, string searchLastCall,
string currentLatestPush, string searchLatestPush,
string currentFilter, string searchString,
string currentDate, string searchDate,
DateTime? start, DateTime? end,
int? pageNumber,
int PS,
string searchPageSize, string currentPageSize,
string p = null)
{
int pageSize = 10;
int num = _context.AppUsers.Count();
var appusers = from a in _context.AppUsers
select a;
var appid = from aid in _context.AppUsers
select aid;
//If Search For Adding PageNumber + searchFilter in Url
if (searchString != null)
{
pageNumber = 1;
}
else
{
searchString = currentFilter;
}
if (searchId != null)
{
pageNumber = 1;
}
else
{
searchId = currentId;
}
if (searchTotalCalls != null)
{
pageNumber = 1;
}
else
{
searchTotalCalls = currentTotalCalls;
}
//Filters Text the Database
ViewData["CurrentFilter"] = searchString;
if (!String.IsNullOrEmpty(searchString))
{
appusers = appusers.Where(s => s.Surname.Contains(searchString)
|| s.FirstName.Contains(searchString));
num = appusers.Where(s => s.Surname.Contains(searchString)
|| s.FirstName.Contains(searchString)).Count();
}
ViewData["CurrentId"] = searchId;
if (!String.IsNullOrEmpty(searchId))
{
var ToId = Int32.Parse(searchId);
appusers = appusers.Where(s => s.Id.ToString().Contains(searchId));
num = appusers.Where(s => s.Id.ToString().Contains(searchId)).Count();
}
ViewData["CurrentTotalCalls"] = searchTotalCalls;
if (!String.IsNullOrEmpty(searchTotalCalls))
{
var ToId = Int32.Parse(searchTotalCalls);
appusers = appusers.Where(s => s.TotalCalls.ToString().Contains(searchTotalCalls));
num = appusers.Where(s => s.TotalCalls.ToString().Contains(searchTotalCalls)).Count();
}
ViewData["currentPageSize"] = searchPageSize;
if (!String.IsNullOrEmpty(searchPageSize))
{
pageSize = Int32.Parse(searchPageSize);
}
ViewData["currentLastCall"] = searchLastCall;
if (!String.IsNullOrEmpty(searchLastCall))
{
DateTime dtLastCall = DateTime.Parse(searchLastCall);
appusers = appusers.Where(s => s.LastCall >= dtLastCall.Date && s.LastCall < dtLastCall.AddDays(1));
num = appusers.Where(s => s.LastCall >= dtLastCall.Date && s.LastCall < dtLastCall.AddDays(1)).Count();
}
ViewData["CurrentLatestPush"] = searchLatestPush;
if (!String.IsNullOrEmpty(searchLatestPush))
{
DateTime dtLatestPush = DateTime.Parse(searchLatestPush);
appusers = appusers.Where(s => s.PushUpdate >= dtLatestPush.Date && s.PushUpdate < dtLatestPush.AddDays(1));
num = appusers.Where(s => s.PushUpdate>= dtLatestPush.Date && s.PushUpdate < dtLatestPush.AddDays(1)).Count();
}
// Populate DropDownList
ViewData["CurrentS"] = PS;
if (PS == 10 )
{
pageSize = 10;
}else if(PS == 20)
{
pageSize = 20;
}
else if(PS == 50)
{
pageSize = 50;
}
//Page Size Display Calculations
ViewBag.Count = num;
if (pageSize > num)
{
ViewBag.Count = num;
ViewBag.pSize = num;
}
else
{
ViewBag.Count = num;
ViewBag.pSize = pageSize;
}
//PageNumber bellow 0 becames 1 , Error sovled
if (pageNumber == 0){
pageNumber = 1;
};
return View(await PushNotificationApp.PaginatedList<AppUser>.CreateAsync(appusers.AsNoTracking(), appid.AsNoTracking(), pageNumber ?? 1, pageSize));
}
Index Page :
#model PaginatedList<PushNotificationApp.Models.AppUser>
#{
ViewData["Title"] = "Index";
}
#*Header With Filter Top*#
<div class="Application-header">
#*Header*#
<h1 class="display-5">PUSH NOTIFICATION APPLICATION</h1>
#*Date Filter Top*#
<div class="d-flex justify-content-between">
#using (Html.BeginForm("Index", "AppUsers", new { id = "filterForm" }))
{
<div class="d-flex align-items-center">
<span class="font-weight-bold">Start Date :</span> <input type="date" name="start">
<span class="font-weight-bold m-3">End Date :</span> <input type="date" name="end" />
<span class="font-weight-bold m-3">Trips :</span> <input size="3" type="text" name="SearchTrips" value="#ViewData["CurrentTrips"]" />
#*<input class="l MainButton" type="submit" value="" OnClick="Button1_Click" />*#
<button class="m-3" type="submit" value="submit" OnClick="Button1_Click">
<svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-search" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M10.442 10.442a1 1 0 0 1 1.415 0l3.85 3.85a1 1 0 0 1-1.414 1.415l-3.85-3.85a1 1 0 0 1 0-1.415z" />
<path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11zM13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0z" />
</svg>
</button>
</div>
}
<div>
<!-- Paging Size DropDown -->
<form asp-action="Index" method="get">
<select id="PageSelection" name="PS" value="#ViewData["CurrentP"]">
<option value="">Size</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
#*<button type="submit">Ho</button>*#
</form>
</div>
</div>
</div>
#*Declare next - Prev for footer table*#
#{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
#*2 Flex Tables*#
<div class="container">
<div class="row">
<div class="col-sm-8" style="background-color:lightgray; padding:0px!important;">
<div class="table-container ">
#*First Table with Data*#
<table class="table">
<thead class=" Left-Table-Header">
<tr>
<th>
<p>CHECK</p>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input type="checkbox" id="selectAll" /></p>
</div>
</form>
</th>
<th>
<p>ID</p>
<form asp-action="Index" asp-route-currentFilter="#ViewData["CurrentFilter"]" method="get">
<div class="form-actions no-color">
<p><input size="2" type="text" name="SearchId" value="#ViewData["CurrentId"]" /></p>
</div>
</form>
</th>
<th colspan="4">
<p>NAME</p>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input size="20" type="text" name="SearchString" value="#ViewData["CurrentFilter"]" /></p>
</div>
</form>
</th>
<th colspan="2">
<p>TOTAL CALLS</p>
<div>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input size="3" type="text" name="searchTotalCalls" value="#ViewData["CurrentTotalCalls"]" /></p>
</div>
</form>
</div>
</th>
<th colspan="2">
<p>LAST CALL</p>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input size="8" type="text" name="SearchLastCall" value="#ViewData["CurrentLastCall"]" /> </p>
</div>
</form>
</th>
<th colspan="2">
<p>LATEST PUSH</p>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input size="8" type="text" name="SearchLatestPush" value="#ViewData["CurrentLatestPush"]" /></p>
</div>
</form>
</th>
</tr>
</thead>
<tbody id="myTable" class="Table-Rows">
#foreach (var item in Model)
{
<tr>
<td>
<div id="chex"> <input type="checkbox" id="#item.Id" class="checkBoxes" /> </div>
</td>
<td> #Html.DisplayFor(modelItem => item.Id)</td>
<td colspan="4">
<div onclick="showMore('#item.UserEmail');" id="NameDetails" class="d-flex justify-content-between align-items-center">
<div>
#Html.DisplayFor(modelItem => item.FirstName)
</div>
<div>
<svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-caret-down-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M7.247 11.14L2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z" />
</svg>
</div>
</div>
<div id="#item.UserEmail" style="display:none;">
#Html.DisplayFor(modelItem => item.Surname)
<br />
#Html.DisplayFor(modelItem => item.UserEmail)
<br />
#Html.DisplayFor(modelItem => item.MobilePhone)
</div>
</td>
<td colspan="2">#Html.DisplayFor(modelItem => item.TotalCalls)</td>
<td colspan="2">#Html.DisplayFor(modelItem => item.LastCall)</td>
<td colspan="2"> #Html.DisplayFor(modelItem => item.PushUpdate)</td>
</tr>
}
</tbody>
</table>
#*div container with pagination*#
<div class="d-flex justify-content-between">
#* Prev Next Buttons*#
<div class="p-2 bd-highlight">
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
<a class="page-link MainButton" asp-action="Index"
asp-route-pageNumber="#(Model.PageIndex - 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
asp-route-currentId="#ViewData["CurrentId"]"
asp-route-currentTotalCalls="#ViewData["CurrentTotalCalls"]"
asp-route-currentLastCall="#ViewData["CurrentLastCall"]"
asp-route-currentLatestPush="#ViewData["CurrentLatestPush"]"
asp-route-currentPageSize="#ViewData["CurrentPageSize"]"
class="page-link #prevDisabled">
Previous
</a>
</li>
<li class="page-item">
<a class="page-link MainButton" asp-action="Index"
asp-route-pageNumber="#(Model.PageIndex + 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
asp-route-currentId="#ViewData["CurrentId"]"
asp-route-currentTotalCalls="#ViewData["CurrentTotalCalls"]"
asp-route-currentLastCall="#ViewData["CurrentLastCall"]"
asp-route-currentLatestPush="#ViewData["CurrentLatestPush"]"
asp-route-currentPageSize="#ViewData["CurrentPageSize"]"
class="btn btn-default #nextDisabled">
Next
</a>
</li>
</ul>
</nav>
</div>
#*Table total entries and rows*#
#{
int data = ViewBag.Count;
var i = (Model.PageIndex);
var y = ViewBag.pSize;
if (data < y) { y = data; } else { y = y * i; }
}
<p><b>#y</b> out of <b>#data</b></p>
#*Clear Button*#
<div class="p-2 bd-highlight">
<a asp-action="Index" class="MainButton">Clear</a>
</div>
</div>
</div>
</div>
#*This is the second Table aligned Flex*#
<div class="col-sm-4" style="background-color:lightgray; padding:0px!important; border-left: 1px solid white;">
<div class="text-area">
<table id="myTable" class="table">
<thead class="Right-Table-Header">
<tr>
<th> <span class="Right-Table-Header-Text">PUSH NOTIFICATION MESSAGE</span></th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea class="txtArea" id="textAreaMSG" name="w3review" rows="10" cols="60">Enter the text you want to sent as a Push Notification...</textarea></td>
</tr>
</tbody>
<thead class="Right-Table-Header">
<tr>
<th><span class="Right-Table-Ready-Msg">READY MESSAGES</span></th>
</tr>
</thead>
<tbody>
#*Radio Boxes With Ready Msg*#
<tr>
<td>
<div class="form-check RadioBoxes">
<input class="form-check-input" type="radio" name="exampleRadios" id="Radio1" value="option1" onclick="radioMsg()">
<label class="form-check-label" for="Radio1" id="radioMessage1">Bravo!You have the most trips this Week.</label>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-check RadioBoxes">
<input class="form-check-input" type="radio" name="exampleRadios" id="Radio2" value="option2" onclick="radioMsg()">
<label class="form-check-label" for="Radio2" id="radioMessage2">You travelled a lot this Month!</label>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-check RadioBoxes">
<input class="form-check-input" type="radio" name="exampleRadios" id="Radio3" value="option3" onclick="radioMsg()">
<label class="form-check-label" for="Radio3" id="radioMessage3">Congratulations!You have the most trips this Year.</label>
</div>
</td>
</tr>
<tr>
#*Push/Push history Buttons*#
<td class="d-flex justify-content-between">
#*Push History button*#
<a class="MainButton" asp-area="" asp-controller="AppUsers" asp-action="Index1">Push History</a>
#*Push Button with confirmation box*#
<button type="button" class="MainButtonPush" data-toggle="modal" data-target="#exampleModalCenter" onclick="getText()">
Push
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Push Notification Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modal_body_text">
Are are about to sent Push Notification to ... with the following text : ....
</div>
<div class="modal-footer d-flex justify-content-between">
<button type="button" class="MainButton" data-dismiss="modal">Close</button>
<button class="MainButtonPush" onclick="myf()">Push</button>
</div>
</div>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
I know I have many things I need to solve to have a complete clean code and some parts are useless but I am a beginner and I am trying to learn
Your code is a bit in a mess.
1.Your view contains #ViewData["CurrentP"] but in your action is #ViewData["CurrentS"].
2.The code below is not used to populate DropDownList:
// Populate DropDownList
ViewData["CurrentS"] = PS;
if (PS == 10 )
{
pageSize = 10;
}else if(PS == 20)
{
pageSize = 20;
}
else if(PS == 50)
{
pageSize = 50;
}
You have hard-coded the DropDownList in razor view:
Paging Size DropDown
<form asp-action="Index" method="get">
<select id="PageSelection" name="PS" value="#ViewData["CurrentS"]">
<option value="">Size</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
<button type="submit">Ho</button>
</form>
3.In official document,PaginatedList method contains three paramaters,not sure why do you pass four paramater,and both of the appid and appusers are the same object.
https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page?view=aspnetcore-5.0#add-paging-to-students-index
I have changed your code and provide the working code below:
View:
#model PaginatedList<AppUser>
Header With Filter Top
<div class="Application-header">
Header
<h1 class="display-5">PUSH NOTIFICATION APPLICATION</h1>
Date Filter Top
<div class="d-flex justify-content-between">
#using (Html.BeginForm("Index", "AppUsers", new { id = "filterForm" }))
{
<div class="d-flex align-items-center">
<span class="font-weight-bold">Start Date :</span> <input type="date" name="start">
<span class="font-weight-bold m-3">End Date :</span> <input type="date" name="end" />
<span class="font-weight-bold m-3">Trips :</span> <input size="3" type="text" name="SearchTrips" value="#ViewData["CurrentTrips"]" />
<input class="l MainButton" type="submit" value="" OnClick="Button1_Click" />
<button class="m-3" type="submit" value="submit" OnClick="Button1_Click">
<svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-search" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M10.442 10.442a1 1 0 0 1 1.415 0l3.85 3.85a1 1 0 0 1-1.414 1.415l-3.85-3.85a1 1 0 0 1 0-1.415z" />
<path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11zM13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0z" />
</svg>
</button>
</div>
}
<div>
Paging Size DropDown
<form asp-action="Index" method="get"> //change here....
<select id="PageSelection" name="PS" value="#ViewData["CurrentS"]">
<option value="">Size</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
<button type="submit">Ho</button>
</form>
</div>
</div>
</div>
Declare next - Prev for footer table
#{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
2 Flex Tables
<div class="container">
<div class="row">
<div class="col-sm-8" style="background-color:lightgray; padding:0px!important;">
<div class="table-container ">
First Table with Data
<table class="table">
<thead class=" Left-Table-Header">
<tr>
<th>
<p>CHECK</p>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input type="checkbox" id="selectAll" /></p>
</div>
</form>
</th>
<th>
<p>ID</p>
<form asp-action="Index" asp-route-currentFilter="#ViewData["CurrentFilter"]" method="get">
<div class="form-actions no-color">
<p><input size="2" type="text" name="SearchId" value="#ViewData["CurrentId"]" /></p>
</div>
</form>
</th>
<th colspan="4">
<p>NAME</p>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input size="20" type="text" name="SearchString" value="#ViewData["CurrentFilter"]" /></p>
</div>
</form>
</th>
<th colspan="2">
<p>TOTAL CALLS</p>
<div>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input size="3" type="text" name="searchTotalCalls" value="#ViewData["CurrentTotalCalls"]" /></p>
</div>
</form>
</div>
</th>
<th colspan="2">
<p>LAST CALL</p>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input size="8" type="text" name="SearchLastCall" value="#ViewData["CurrentLastCall"]" /> </p>
</div>
</form>
</th>
<th colspan="2">
<p>LATEST PUSH</p>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p><input size="8" type="text" name="SearchLatestPush" value="#ViewData["CurrentLatestPush"]" /></p>
</div>
</form>
</th>
</tr>
</thead>
<tbody id="myTable" class="Table-Rows">
#foreach (var item in Model)
{
<tr>
<td>
<div id="chex"> <input type="checkbox" id="#item.Id" class="checkBoxes" /> </div>
</td>
<td> #Html.DisplayFor(modelItem => item.Id)</td>
<td colspan="4">
<div onclick="showMore('#item.UserEmail');" id="NameDetails" class="d-flex justify-content-between align-items-center">
<div>
#Html.DisplayFor(modelItem => item.FirstName)
</div>
<div>
<svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-caret-down-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M7.247 11.14L2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z" />
</svg>
</div>
</div>
<div id="#item.UserEmail" style="display:none;">
#Html.DisplayFor(modelItem => item.Surname)
<br />
#Html.DisplayFor(modelItem => item.UserEmail)
<br />
#Html.DisplayFor(modelItem => item.MobilePhone)
</div>
</td>
<td colspan="2">#Html.DisplayFor(modelItem => item.TotalCalls)</td>
<td colspan="2">#Html.DisplayFor(modelItem => item.LastCall)</td>
<td colspan="2"> #Html.DisplayFor(modelItem => item.PushUpdate)</td>
</tr>
}
</tbody>
</table>
div container with pagination
<div class="d-flex justify-content-between">
Prev Next Buttons
<div class="p-2 bd-highlight">
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
<a class="page-link MainButton" asp-action="Index"
asp-route-pageNumber="#(Model.PageIndex - 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
asp-route-currentId="#ViewData["CurrentId"]"
asp-route-currentTotalCalls="#ViewData["CurrentTotalCalls"]"
asp-route-currentLastCall="#ViewData["CurrentLastCall"]"
asp-route-currentLatestPush="#ViewData["CurrentLatestPush"]"
asp-route-currentPageSize="#ViewData["CurrentPageSize"]"
class="page-link #prevDisabled">
Previous
</a>
</li>
<li class="page-item">
<a class="page-link MainButton" asp-action="Index"
asp-route-pageNumber="#(Model.PageIndex + 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
asp-route-currentId="#ViewData["CurrentId"]"
asp-route-currentTotalCalls="#ViewData["CurrentTotalCalls"]"
asp-route-currentLastCall="#ViewData["CurrentLastCall"]"
asp-route-currentLatestPush="#ViewData["CurrentLatestPush"]"
asp-route-currentPageSize="#ViewData["CurrentPageSize"]"
class="btn btn-default #nextDisabled">
Next
</a>
</li>
</ul>
</nav>
</div>
Table total entries and rows
#{
int data = ViewBag.Count;
var i = (Model.PageIndex);
var y = ViewBag.pSize;
if (data < y) { y = data; } else { y = y * i; }
}
<p><b>#y</b> out of <b>#data</b></p>
Clear Button
<div class="p-2 bd-highlight">
<a asp-action="Index" class="MainButton">Clear</a>
</div>
</div>
</div>
</div>
This is the second Table aligned Flex
<div class="col-sm-4" style="background-color:lightgray; padding:0px!important; border-left: 1px solid white;">
<div class="text-area">
<table id="myTable" class="table">
<thead class="Right-Table-Header">
<tr>
<th> <span class="Right-Table-Header-Text">PUSH NOTIFICATION MESSAGE</span></th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea class="txtArea" id="textAreaMSG" name="w3review" rows="10" cols="60">Enter the text you want to sent as a Push Notification...</textarea></td>
</tr>
</tbody>
<thead class="Right-Table-Header">
<tr>
<th><span class="Right-Table-Ready-Msg">READY MESSAGES</span></th>
</tr>
</thead>
<tbody>
Radio Boxes With Ready Msg
<tr>
<td>
<div class="form-check RadioBoxes">
<input class="form-check-input" type="radio" name="exampleRadios" id="Radio1" value="option1" onclick="radioMsg()">
<label class="form-check-label" for="Radio1" id="radioMessage1">Bravo!You have the most trips this Week.</label>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-check RadioBoxes">
<input class="form-check-input" type="radio" name="exampleRadios" id="Radio2" value="option2" onclick="radioMsg()">
<label class="form-check-label" for="Radio2" id="radioMessage2">You travelled a lot this Month!</label>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-check RadioBoxes">
<input class="form-check-input" type="radio" name="exampleRadios" id="Radio3" value="option3" onclick="radioMsg()">
<label class="form-check-label" for="Radio3" id="radioMessage3">Congratulations!You have the most trips this Year.</label>
</div>
</td>
</tr>
<tr>
Push/Push history Buttons
<td class="d-flex justify-content-between">
Push History button
<a class="MainButton" asp-area="" asp-controller="AppUsers" asp-action="Index1">Push History</a>
Push Button with confirmation box
<button type="button" class="MainButtonPush" data-toggle="modal" data-target="#exampleModalCenter" onclick="getText()">
Push
</button>
Modal
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Push Notification Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modal_body_text">
Are are about to sent Push Notification to ... with the following text : ....
</div>
<div class="modal-footer d-flex justify-content-between">
<button type="button" class="MainButton" data-dismiss="modal">Close</button>
<button class="MainButtonPush" onclick="myf()">Push</button>
</div>
</div>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
Controller:
public async Task<IActionResult> Index(String currentId, string searchId,
String currentTotalCalls, string searchTotalCalls,
string currentLastCall, string searchLastCall,
string currentLatestPush, string searchLatestPush,
string currentFilter, string searchString,
string currentDate, string searchDate,
DateTime? start, DateTime? end,
int? pageNumber,
int PS,
string searchPageSize, int currentPageSize,
string p = null)
{
int pageSize = 10;
int num = _context.AppUser.Count();
var appusers = from a in _context.AppUser
select a;
//var appid = from aid in _context.AppUsers
//select aid;
//If Search For Adding PageNumber + searchFilter in Url
if (searchString != null)
{
pageNumber = 1;
}
else
{
searchString = currentFilter;
}
if (searchId != null)
{
pageNumber = 1;
}
else
{
searchId = currentId;
}
if (searchTotalCalls != null)
{
pageNumber = 1;
}
else
{
searchTotalCalls = currentTotalCalls;
}
//Filters Text the Database
ViewData["CurrentFilter"] = searchString;
if (!String.IsNullOrEmpty(searchString))
{
//do your stuff...
}
ViewData["CurrentId"] = searchId;
if (!String.IsNullOrEmpty(searchId))
{
//do your stuff...
}
ViewData["CurrentTotalCalls"] = searchTotalCalls;
if (!String.IsNullOrEmpty(searchTotalCalls))
{
//do your stuff...
}
//Begin of change
if (PS!=0|| currentPageSize!=0)
{
if(PS==0)
{
ViewData["CurrentPageSize"] = currentPageSize;
pageSize = currentPageSize;
}
else
{
ViewData["CurrentPageSize"] = PS;
pageSize = PS;
}
}
//ViewData["currentPageSize"] = searchPageSize;
if (!String.IsNullOrEmpty(searchPageSize))
{
ViewData["CurrentPageSize"] = searchPageSize;
pageSize = Int32.Parse(searchPageSize);
}
if(ViewData["CurrentPageSize"] !=null)
{
pageSize = Int32.Parse(ViewData["CurrentPageSize"].ToString());
}
//End of change
ViewData["currentLastCall"] = searchLastCall;
if (!String.IsNullOrEmpty(searchLastCall))
{
//do your stuff...
}
ViewData["CurrentLatestPush"] = searchLatestPush;
if (!String.IsNullOrEmpty(searchLatestPush))
{
//do your stuff...
}
//The code below is useless
// Populate DropDownList
//ViewData["CurrentS"] = PS;
//if (PS == 10)
//{
// pageSize = 10;
//}
//else if (PS == 20)
//{
// pageSize = 20;
//}
//else if (PS == 50)
//{
// pageSize = 50;
//}
//Page Size Display Calculations
ViewBag.Count = num;
if (pageSize > num)
{
ViewBag.Count = num;
ViewBag.pSize = num;
}
else
{
ViewBag.Count = num;
ViewBag.pSize = pageSize;
}
//PageNumber bellow 0 becames 1 , Error sovled
if (pageNumber == 0)
{
pageNumber = 1;
};
return View(await PaginatedList<AppUser>.CreateAsync(appusers.AsNoTracking(), pageNumber ?? 1, pageSize));
}
PaginatedList:
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = source.Count();
var items = source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}

Neither BindingResult nor plain target object for bean name available as request attribute when trying to load a bootstrap modal element

In my JSP im trying to load a bootstrap modal in order to save and edit entities with relevant spring controller methods and model attributes. But when I add this modal i'm getting the following errors. When the tabs are changed, following request is passed to the spring controller which then pass a modal attribute to the view and if thats true the relevant modal shown.
http://localhost:8080/admin/setting/systemRole/load
The error on tomcat log :
DEBUG org.springframework.web.servlet.DispatcherServlet - Could not complete request
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/settings.jsp at line 181
178: <form:form method="post" modelAttribute="user" action="save">
179: <div class="form-group">
180: <label class="col-form-label">User Name</label>
181: <form:input type="text" required="required" class="form-control" path="username"/>
182: <h6 class="fieldError"><form:errors path="username"/></h6>
183: </div>
184: <div class="form-group">
But it works fine for the following request when i change the tab to the users.
http://localhost:8080/admin/setting/systemUser/load
When I remove the code of the modal from the code, the other parts of the UI work fine.
The view (settings.jsp):
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<jsp:include page="header_new.jsp"/>
<div class="page-title-area">
<div class="container-fluid">
<div class="row">
<div class="col-sm-11 col-sm-offset-1 page-title-section">
<h2 class="page-title">
<span>Settings</span>
</h2>
<ul class="page-title__nav common-list nav nav-tabs" style="margin-bottom: -5px">
<li <c:if test="${userTabActive}"> class="active" </c:if>><a data-toggle="tab"
onclick="loadUsers()">Users</a></li>
<li <c:if test="${roleTabActive}"> class="active" </c:if>><a data-toggle="tab"
onclick="loadRoles()">Roles</a></li>
</ul>
</div>
</div>
</div>
</div>
<script>
function loadUsers() {
window.location = '/admin/setting/systemUser/load';
}
function loadRoles() {
window.location = '/admin/setting/systemRole/load';
}
$(document).ready(function () {
$('#usersTable').DataTable({})
$('#rolesTable').DataTable({})
});
function loadUser(id) {
window.location = 'loadUser?id=' + id;
}
function loadRole(id) {
window.location = 'loadRole?id=' + id;
}
function deleteUser(id) {
$('#user-id').val(id);
$('#userDeleteModal').modal("show");
}
var checkPasswords = function () {
if (document.getElementById('password').value ==
document.getElementById('confirm-password').value) {
document.getElementById('passwordsMatchMessage').style.color = 'green';
document.getElementById('passwordsMatchMessage').innerHTML = 'Passwords are matching';
document.getElementById("submitButton").disabled = false;
} else {
document.getElementById('passwordsMatchMessage').style.color = 'red';
document.getElementById('passwordsMatchMessage').innerHTML = 'Passwords are not matching';
document.getElementById("submitButton").disabled = true;
}
}
</script>
<c:if test="${loadUserModal}">
<script>
window.alert("user edit modal");
$("#userSaveModal").modal()
document.getElementById('userModalLabel').innerHTML = 'Edit User';
document.getElementById('password').value = '';
</script>
</c:if>
<c:if test="${saveUser}">
<script>
window.alert("user save modal");
$("#userSaveModal").modal()
document.getElementById('userModalLabel').innerHTML = 'Save User';
</script>
</c:if>
<c:if test="${loadRoleModal}">
<script>
window.alert("role modal");
$("#roleSaveModal").modal()
document.getElementById('roleModalLabel').innerHTML = 'Save Role';
</script>
</c:if>
<!-- Begin page content -->
<div class="container-fluid">
<div class="row">
<jsp:include page="components/common/sidemenu.jsp">
<jsp:param name="activeTab" value="settings"/>
</jsp:include>
<div class="tab-content">
<div id="merchants" class="tab-pane fade active">
<c:if test="${errorView ne 'E1020'}">
<div class="col-md-11 col-md-offset-1">
<div class="page-card" style="padding-right: 20px;margin-left: 20px;margin-top: 20px">
</div>
</div>
</c:if>
</div>
</div>
</div>
</div>
<c:if test="${viewUsers}">
<div class="tab-content">
<div class="tab-pane fade in active">
<div class="container-fluid">
<div style="padding-top: 10px; padding-right: 20px">
<button type="button" class="btn btn-primary" style="float: right;" onclick="loadUser(0)"><i
class="fa fa-plus" style="margin-right: 5px"></i>New User
</button>
</div>
<div class="row">
<div class="col-md-11 col-md-offset-1">
<div class="page-card">
<div class="page-card__body">
<div class="table-responsive">
<table id="usersTable" class="table table-bordered table-striped dataTable">
<thead>
<tr>
<th>User Name</th>
<th>Name</th>
<th>Status</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.username}</td>
<td>${user.name}</td>
<td>${user.state}</td>
<td>${user.role.roleName}</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal"
onclick="loadUser('${user.id}')">
<i class="fa fa-edit"></i> Edit
</button>
<button type="button" data-toggle="modal" id="delete"
onclick="deleteUser('${user.id}')" name="delete"
class="btn btn-danger">
<i class="fa fa-trash-o"></i> Delete
</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</c:if>
<c:if test="${viewRoles}">
<div class="tab-content">
<div class="tab-pane fade in active">
<div class="container-fluid">
<div style="padding-top: 10px; padding-right: 20px">
<button type="button" class="btn btn-primary" style="float: right;" onclick="loadRole(0)"><i
class="fa fa-plus" style="margin-right: 5px"></i>Add Role
</button>
</div>
<div class="row">
<div class="col-md-11 col-md-offset-1">
<div class="page-card">
<div class="page-card__body">
<div class="table-responsive">
<table id="rolesTable" class="table table-bordered table-striped dataTable">
<thead>
<tr>
<th>Name</th>
<th>Permissions</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${roles}" var="role">
<tr>
<td>${role.roleName}</td>
<td>
<a href="#" data-toggle="popover" data-container="body"
data-content="<c:forEach var="permission" items="${role.permissionList}">
${permission.name}
</c:forEach>">View Permissions</a>
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal"
onclick="loadRole('${role.id}')">
<i class="fa fa-edit"></i> Edit
</button>
<%--<button type="button" class="btn btn-primary" data-toggle="modal"--%>
<%--onclick="editRole('${role.id}','${role.roleName}')" ><i class="fa fa-edit"></i> Edit--%>
<%--</button>--%>
<%--<button type="button" data-toggle="modal" id="delete"--%>
<%--onclick="deleteRole('${role.id}')" name="delete" class="btn btn-danger">--%>
<%--<i class="fa fa-trash-o"></i> Delete--%>
<%--</button>--%>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</c:if>
<div class="modal fade" id="userDeleteModal" tabindex="-1" role="dialog" aria-labelledby="userDeleteModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Delete Record</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you need to remove this record ?
</div>
<form id="systemUserDeleteForm" method="post" class="w3-margin" action="remove">
<input style="visibility: hidden !important;" id="user-id" name="id">
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Delete</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="userSaveModal" tabindex="-1" role="dialog" aria-labelledby="userSaveModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="col-md-4">
<h5 class="modal-title" id="userModalLabel"></h5>
</div>
<div class="col-md-8">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<div class="modal-body">
<form:form method="post" modelAttribute="user" action="save">
<div class="form-group">
<label class="col-form-label">User Name</label>
<form:input type="text" required="required" class="form-control" path="username"/>
<h6 class="fieldError"><form:errors path="username"/></h6>
</div>
<div class="form-group">
<label for="name" class="col-form-label">Name</label>
<form:input type="text" required="required" class="form-control" path="name"/>
<h6 class="fieldError"><form:errors path="name"/></h6>
</div>
<div class="form-group">
<label>Role</label>
<form:select class="form-control"
required="required" path="role.id">
<c:forEach items="${roles}" var="role">
<form:option value="${role.id}" label="${role.roleName}" />
</c:forEach>
</form:select>
</div>
<div class="form-group">
<label for="state">Status</label>
<form:select class="form-control"
required="required" path="state">
<form:option value="ACTIVE" label="ACTIVE"/>
<form:option value="INACTIVE" label="INACTIVE"/>
</form:select>
</div>
<c:if test="${saveUser}">
<div class="form-group">
<label class="col-form-label">Password</label>
<form:input onkeyup='checkPasswords();' type="password" class="form-control"
path="password"/>
<h6 class="fieldError"><form:errors path="password"/></h6>
</div>
<div class="form-group">
<label class="col-form-label">Confirm Password</label>
<input onkeyup='checkPasswords();' type="password" class="form-control" />
</div>
<span id='passwordsMatchMessage'></span>
</c:if>
<c:if test="${not saveUser}">
<%--hidden input value is passed for editing record to avoid getting a null value for the password for user object--%>
<form:input type="hidden" path="password"/>
</c:if>
<form:input type="hidden" name="id" path="id"/>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="submitButton" class="btn btn-primary">Submit</button>
</div>
</form:form>
</div>
</div>
</div>
</div>
<div class="modal fade" id="roleSaveModal" tabindex="-1" role="dialog" aria-labelledby="roleSaveModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<div class="col-md-4" style="float: left">
<h5 class="modal-title" id="roleModalLabel"></h5>
</div>
<div class="col-md-8">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<div class="modal-body">
<form:form method="post" modelAttribute="role" action="save">
<div class="form-group">
<label for="role-name" class="col-form-label">Role Name</label>
<form:input type="text" required="required" class="form-control" id="role-name"
path="roleName"/>
<h6 class="fieldError"><form:errors path="roleName"/></h6>
</div>
<div class="form-group">
<label class="col-form-label">Permissions</label>
<c:forEach items="${permissions}" var="permission">
<div class="check-box" style="padding-left: 20px">
<c:choose>
<c:when test="${permission.checked}">
<form:checkbox value="${permission.id}"
path="checkedPermissions" checked="checked"/>
<label style=" margin-left: 10px">${permission.name}</label>
</c:when>
<c:otherwise>
<form:checkbox value="${permission.id}"
path="checkedPermissions"/>
<label style=" margin-left: 10px">${permission.name}</label>
</c:otherwise>
</c:choose>
</div>
</c:forEach>
</div>
<form:input type="hidden" id="id" name="id" path="id"/>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form:form>
</div>
</div>
</div>
</div>
The users controller :
#Controller
#RequestMapping("/setting/systemUser")
public class SystemUserController {
private final static Logger logger = LoggerFactory.getLogger(SystemUserController.class);
#Autowired
#Qualifier("systemUserValidator")
private Validator validator;
#Autowired
private SystemUserService systemUserService;
#Autowired
private SystemRoleService systemRoleService;
#Autowired
private UserDetailsHelper userDetailsHelper;
#InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
#RequestMapping(value = "/load", method = RequestMethod.GET)
public String viewRoles(Model model) {
loadData(model);
return "settings";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveUser(Model model, #Validated #ModelAttribute("user") SystemUser user, BindingResult result) {
logger.info("User save/update request received [{}]", user.toString());
if (result.hasErrors()) {
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("roles", systemRoleService.getAllUserRoles());
model.addAttribute("loadUserModal", true);
return "settings";
}
systemUserService.saveSystemUser(user);
loadData(model);
return "settings";
}
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String deleteRole(Model model, #RequestParam("id") Long id) {
SystemUser user = systemUserService.getSystemUser(id);
logger.info("User remove request received [{}]", user.toString());
systemUserService.deleteUser(user);
loadData(model);
return "settings";
}
#RequestMapping(value = "/loadUser", method = RequestMethod.GET)
public String loadUser(Model model, #RequestParam("id") Long id) {
loadData(model);
model.addAttribute("user", systemUserService.getSystemUser(id));
model.addAttribute("loadUserModal", true);
if (id == 0){
model.addAttribute("saveUser", true);
}
model.addAttribute("userTabActive", true);
model.addAttribute("viewUsers", true);
return "settings";
}
private void loadData(Model model) {
model.addAttribute("userDetails", userDetailsHelper.getSystemUser().getUsername());
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("roles", systemRoleService.getAllUserRoles());
model.addAttribute("user", new SystemUser());
model.addAttribute("userTabActive", true);
model.addAttribute("viewUsers", true);
}
}
The roles controller :
#Controller
#RequestMapping("/setting/systemRole")
public class SystemRoleController {
#Autowired
#Qualifier("systemRoleValidator")
private Validator validator;
#Autowired
private SystemRoleService roleService;
#Autowired
private UserDetailsHelper userDetailsHelper;
#InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
#RequestMapping(value = "/load", method = RequestMethod.GET)
public String viewRoles(Model model) {
loadData(model);
return "settings";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveRole(Model model, #Validated #ModelAttribute("role") SystemRole role, BindingResult result) {
logger.info("Role save/update request received [{}]", role.toString());
if (result.hasErrors()) {
model.addAttribute("roles", roleService.getAllUserRoles());
model.addAttribute("permissions", roleService.getAllPermission());
model.addAttribute("loadRoleModal", true);
return "settings";
}
roleService.saveSystemRole(role);
loadData(model);
return "settings";
}
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String deleteRole(Model model, #RequestParam("id") Long id) {
roleService.deleteRole(roleService.getUserRole(id));
loadData(model);
return "settings";
}
#RequestMapping(value = "/loadRole", method = RequestMethod.GET)
public String loadRole(Model model, #RequestParam("id") Long id) {
loadData(model);
model.addAttribute("loadRoleModal", true);
model.addAttribute("role", roleService.getUserRole(id));
SystemRole role = roleService.getUserRole(id);
model.addAttribute("permissions", roleService.getAllPermission(role));
return "settings";
}
private void loadData(Model model) {
model.addAttribute("roles", roleService.getAllUserRoles());
model.addAttribute("permissions", roleService.getAllPermission());
model.addAttribute("role", new SystemRole());
model.addAttribute("userDetails", userDetailsHelper.getSystemUser().getUsername());
model.addAttribute("roleTabActive", true);
model.addAttribute("viewRoles", true);
}
}
SystemRole model class :
#Entity(name = "system_user_role")
public class SystemRole implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#Column(name = "name")
private String roleName;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
#JoinTable(name = "system_role_permission", joinColumns = {
#JoinColumn(name = "id", nullable = false)},
inverseJoinColumns = {#JoinColumn(name = "permission_id", nullable = false)})
private List<Permission> permissionList = new ArrayList<Permission>();
#Transient
private List<Long> checkedPermissions = new ArrayList<>();
public SystemRole() {
}
The HTML views (when the modals are removed):
This doesnt seem to load when the modal are added. And the delete modal seems to work fine. What could be going wrong in here?

Why am I getting 'TypeError: Cannot read property 'slice' of undefined'?

I am working on a small project. It is an ASP.NET MVC/Angular5 project. I am simply trying to populate a tableView (PrimeNG) with data that is selected from a Modal or PrimeNG Dialog.
Here is a snipit of the relevent ts file:
displayIndexDialog: boolean;
index: Index = {};
selectedIndex: Index;
newIndex: boolean;
indexes: Index[];
//METHODS
getIndexes() {
this._indexesService.getIndexes().subscribe(indexes => this.indexList = indexes);
}
showIndexAdd() {
this.newIndex = true;
this.selectedIndex = {};
this.displayIndexDialog = true;
this.getIndexes();
}
closeIndexDialog() {
this.displayIndexDialog = false;
}
saveIndex() {
let index = [...this.indexes];
if (this.newIndex) {
index.push(this.index);
}else
index[this.indexes.indexOf(this.selectedIndex)] = this.index;
this.indexes = index;
this.indexes = null;
this.displayIndexDialog = false;
};
//INTERFACE
interface Index {
defaultIndex?;
pK_Index ?;
description ?;
}
Here is the relevent HTML:
<!--INDEX TABLE-->
<p-table [columns]="cols3" [value]="indexes">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
<ng-template pTemplate="summary" let-rowData>
<div style="text-align:left">
<button class="btn-cblt" type="button" pButton icon="fa-plus" (click)="showIndexAdd()" label="Add"></button>
</div>
</ng-template>
</p-table><br />
<h4>Differentials</h4>
<p-table [columns]="cols2" [value]="diffs1">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr [pSelectableRow]="rowData">
<td *ngFor="let col of columns">
{{rowData[col.field]}}
</td>
</tr>
</ng-template>
<ng-template pTemplate="summary" let-rowData>
<div style="text-align:left">
<button class="btn-cblt" type="button" pButton icon="fa-plus" (click)="showDifferentialAdd()" label="Add"></button>
</div>
</ng-template>
</p-table>
<!--ADD INDEX DIALOG-->
<p-dialog class="sha" header="Add Index" [(visible)]="displayIndexDialog" [responsive]="true" showEffect="fade" [modal]="true" [width]="600" [height]="300">
<div class="ui-g ui-fluid" *ngIf="selectedIndex">
<div class="ui-g-12">
<div class="ui-g-4">
<label for="Index">Index</label>
</div>
<div class="ui-g-8">
<p-dropdown id="index" placeholder="Select an Index" [options]="indexList" [(ngModel)]="selectedIndex.description" [ngModelOptions]="{standalone: true}" optionLabel="description" [showClear]="true"> </p-dropdown>
</div>
</div>
<div class="ui-g-12">
<div class="ui-g-4">
<label for="isDefault">Default Index?</label>
</div>
<div class="ui-g-8">
<p-checkbox name="defaultIndex" id="isDefault" [(ngModel)]="selectedIndex.defaultIndex"></p-checkbox>
</div>
</div>
<div id="indexName">{{index.pK_Index ? index.pK_Index: ' ' }}</div>
</div>
<div class="ui-dialog-buttonpane ui-helper-clearfix">
<button class="btn-cblt" type="button" pButton icon="fa-check" (click)="saveIndex()" label="Save"></button>
<button class="btn-cblt-danger" type="button" pButton icon="fa-close" (click)="closeIndexDialog()" label="Cancel"></button>
</div>
</p-dialog>
Every time I click the 'save' button on the dialog, in the console I get:

I have been staring at this for 3 days now and Have no idea why this isn't working. Please help!
The Resolution to this was #ConnorsFan 's suggestion. The indexes were not initialized. Setting indexes: Index[] = [] fixed the issue. Thank you #ConnorsFan.

How to separate 2 POST and 2 GET method in 1 controller class in spring mvc

i am developing web app that have a transaction for buying a product and that transaction required a customer data. so in that transaction form, i add a modal form for user to add a new customer data.
here currently it's look like :
link to open the add new customer modal form
modal form to add customer
And here my full controller class :
#Controller
public class InvoiceProductController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private MsEmployeeService msEmployeeService;
#Autowired
private MsCustomerService msCustomerService;
#Autowired
CustomerFormValidator customerFormValidator;
#Autowired
private MsLocationService msLocationService;
#Autowired
private MsReligionService msReligionService;
// Set a form validator
#InitBinder("msCustomer")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(customerFormValidator);
}
#RequestMapping(value = "/trproduct", method = RequestMethod.GET)
public ModelAndView trproduct(Locale locale, HttpSession session) {
ModelAndView mav = new ModelAndView("entryinvoiceproduct");
MsUser loggedInUser = (MsUser) session.getAttribute("loggedInUser");
List<MsEmployee> msEmployee = msEmployeeService.findEmployeeByJobsAndLocation("BEAUTY CONSULTANT",
(short) loggedInUser.getMsLocation().getId());
List<MsCustomer> msCustomer = msCustomerService.findAll();
mav.addObject("listCustomer", msCustomer);
mav.addObject("beautyConsultant", msEmployee);
mav.addObject("defaultLocation", loggedInUser);
return mav;
}
#RequestMapping(value = "/trproduct", method = RequestMethod.POST)
public String saveCustomer(#ModelAttribute("customerForm") #Validated MsCustomer msCustomer, BindingResult result,
Model model, final RedirectAttributes redirectAttributes) {
logger.debug("saveOrUpdateUser() : {}", msCustomer);
if (result.hasErrors()) {
populateDefaultModel(model);
return "/trproduct";
} else {
// Add message to flash scope
redirectAttributes.addFlashAttribute("css", "success");
if (msCustomer.isNew()) {
redirectAttributes.addFlashAttribute("msg", "User added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "User updated successfully!");
}
msCustomerService.persist(msCustomer);
// POST/REDIRECT/GET
return "/trproduct";
// POST/FORWARD/GET
// return "user/list";
}
}
// show add customer form
#RequestMapping( method = RequestMethod.GET)
public String showAddCustomerForm(Model model, HttpSession session) {
logger.debug("showAddCustomerForm()");
MsCustomer msCustomer = new MsCustomer();
MsUser loggedInUser = (MsUser) session.getAttribute("loggedInUser");
msCustomer.setUpdateUserId(loggedInUser.getId());
msCustomer.getMsLocation().setId(loggedInUser.getMsLocation().getId());
model.addAttribute("customerForm", msCustomer);
populateDefaultModel(model);
return "";
}
private void populateDefaultModel(Model model) {
List<MsLocation> msLocation = msLocationService.findAll();
model.addAttribute("locationList", msLocation);
List<MsReligion> msReligion = msReligionService.findAll();
model.addAttribute("religionList", msReligion);
}
}
and here my jsp, that calling the modal form in it :
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- CSS -->
<link href='<c:url value="/resources/datatables/datatables.css" />'
rel="stylesheet">
<script src="<c:url value="/resources/datatables/datatables.js" />"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#invoicedtls').DataTable({
"pageLength" : 8,
"lengthMenu" : [ 8, 16, 32, 64, 100 ],
select : true
});
$('#invoicepayments').DataTable({
"pageLength" : 8,
"lengthMenu" : [ 8, 16, 32, 64, 100 ],
select : true
});
$('#existingcustomer').DataTable({
"pageLength" : 8,
"lengthMenu" : [ 8, 16, 32, 64, 100 ],
select : true
});
// $("body").on("click", ".use-address", function() {
// var id = $(this).closest("tr").find(".custid").text();
// var name = $(this).closest("tr").find(".custname").text();
// alert(id + " , " + name);
// });
});
</script>
<div class="panel panel-default">
<div class="panel-heading">
<h4>Invoice Header</h4>
</div>
<div class="panel-body">
<form role="form">
<div class="col-lg-4">
<label>Customer :</label>
<div class="input-group">
<input type="text" class="form-control text-uppercase">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle"
data-toggle="dropdown">
Customer <span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right">
<li><a data-toggle="modal" data-target="#modalNewCustomer">New</a></li>
<li><a data-toggle="modal"
data-target="#modalExistingCustomer">Existing</a></li>
</ul>
</div>
<!-- /btn-group -->
</div>
<!-- /input-group -->
</div>
<div class="col-lg-3">
<label>Beauty Consultant :</label> <select id="disabledSelect"
class="form-control">
<option value="-1">Select a Beauty Consultant</option>
<c:forEach items="${beautyConsultant}" var="bc">
<option value="${bc.id}">${bc.name}</option>
</c:forEach>
</select>
</div>
</form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<div class="form-group pull-right">
<button class="btn btn-primary pull-right">Add New Product</button>
</div>
<h4>Product List</h4>
</div>
<div class="panel-body">
<!-- <table class="table table-striped table-hover"> -->
<table id="invoicedtls" class="display highlight">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Qty</th>
<th>Discount Value</th>
<th>Discount Percent</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<div class="form-group pull-right">
<button class="btn btn-primary pull-right">Add New Payment</button>
</div>
<h4>Payment List</h4>
</div>
<div class="panel-body">
<!-- <table class="table table-striped table-hover"> -->
<table id="invoicepayments" class="display highlight">
<thead>
<tr>
<th>Pay With</th>
<th>Bank Name</th>
<th>Cardholder Name</th>
<th>Card No</th>
<th>Card Expired</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- Modal Existing Customer -->
<div class="modal fade" id="modalExistingCustomer" tabindex="-1"
role="dialog" aria-labelledby="modalExistingCustomerLabel">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="modalExistingCustomerLabel">Select
Existing Customer</h4>
</div>
<div class="modal-body">
<!-- <table class="table table-striped table-hover"> -->
<table id="existingcustomer" class="display compact">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Sex</th>
<th>Origin</th>
<th>Religion</th>
<th>Option</th>
</tr>
</thead>
<tbody>
<c:forEach var="customer" items="${listCustomer}">
<tr>
<td class="custid">${customer.id}</td>
<td class="custname">${customer.firstName}</td>
<td>${customer.sex}</td>
<td>${customer.msLocation.name}</td>
<td>${customer.msReligion.name}</td>
<td>
<button class="btn btn-link btn-xs use-address">Use</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Select
Customer</button>
</div>
</div>
</div>
</div>
<!-- Modal New Customer -->
<div class="modal fade" id="modalNewCustomer" tabindex="-1"
role="dialog" aria-labelledby="modalNewCustomerLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="modalNewCustomerLabel">Entry New
Customer</h4>
</div>
<div class="modal-body">
<form id="newCustomer" role="form" action="/admin/users/update" method="post">
<input id="id" name="id" placeholder="Id" value="0" type="hidden"
value="0" />
<div class="form-group">
<label for="firstName">First Name:</label> <input id="firstName"
name="firstName" placeholder="First Name" class="form-control"
type="text" value="" />
</div>
<div class="form-group">
<label for="lastName">Last Name:</label> <input id="lastName"
name="lastName" placeholder="Last Name" class="form-control"
type="text" value="" />
</div>
<div class="form-group">
<label for="email">Email:</label> <input id="email" name="email"
placeholder="Email" class="form-control" type="text" value="" />
</div>
<div class="form-group">
<label for="password">Password:</label> <input id="password"
name="password" placeholder="Password" class="form-control"
type="text" value="" />
</div>
<!-- /.modal-content -->
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save Customer</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// For demo to fit into DataTables site builder...
$('#invoicedtls').removeClass('display').addClass(
'table table-striped table-hover');
$('#invoicepayments').removeClass('display').addClass(
'table table-striped table-hover');
$('#existingcustomer').removeClass('display').addClass(
'table table-striped table-hover table-compact');
// Jquery draggable
$('.modal-dialog').draggable({
handle : ".modal-header"
});
</script>
What i am confusing is, when using a modal form, in controller class, i cannot separate the #RequestMapping value, because the value will always "/trproduct". In this controller class, i want to save 2 different table (SlInvoiceHdr and MsCustomer), but with the same #RequestMapping value.
I am using the same jsp for the add customer modal.
How can i do it in my controller ?
Thank You
Add the expected parameter to your request mapping
#RequestMapping( method = RequestMethod.GET , params = { "expectedparam" })
1 controller, 2 methods with the same requestMapping, but with different parameters
#RequestMapping(value = "/trproduct", method = RequestMethod.GET) public ModelAndView trproduct(Locale locale, HttpSession session) {
second:
#RequestMapping( method = RequestMethod.GET, params = { "newform" }) public String showAddCustomerForm(Model model, HttpSession session) {
But you have to add the the parameter "newform" to your url, like /trproduct?newform=true

Resources