I have issue while working with MVC.
while running application for the first time I am getting 20 results.On filter I am getting 4 results.I am able to see those 4 result in Model while debugging but on view its not getting updated. I tried ViewData and ViewBag also but the result is Same.
Can anyone help me out?
Following is My IncentiveGroupConroller.cs
public ActionResult IncentiveGroupIndex(int? page)
{
int pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
IPagedList<IncentiveGroup> PAGEDGROUP = null;
List<IncentiveGroup> IncentiveGroups = new List<IncentiveGroup>();
DataSet ds = new DataSet();
ds = SQLDatabaseOperations.ExecuteDataset(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(), CommandType.StoredProcedure, "GetIncentiveGroups");
DataTable dt = new DataTable();
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
IncentiveGroups.Add(new IncentiveGroup(dr));
}
ViewBag.IncentiveGroups = IncentiveGroups;
PAGEDGROUP = IncentiveGroups.ToPagedList(pageIndex, 10);
return View(PAGEDGROUP);
}
[HttpPost]
public ActionResult Filter(IncentiveGroup oIncentiveGroup)
{
IPagedList<IncentiveGroup> PagedIncenticeGroups = null;
List<IncentiveGroup> IncentiveGroups = new List<IncentiveGroup>();
DataSet ds = new DataSet();
ds = SQLDatabaseOperations.ExecuteDataset(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(), CommandType.StoredProcedure, "FilterIncentiveGroups", oIncentiveGroup.IncentiveGroupCode, oIncentiveGroup.IncentiveGroupName, oIncentiveGroup.IncentiveGroupShortName, oIncentiveGroup.IncentiveGroupStatus);
DataTable dt = new DataTable();
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
IncentiveGroups.Add(new IncentiveGroup(dr));
}
ViewBag.IncentiveGroups = IncentiveGroups;
PagedIncenticeGroups = IncentiveGroups.ToPagedList(1, IncentiveGroups.Count);
return View("IncentiveGroupIndex", PagedIncenticeGroups);
// return RedirectToAction("IncentiveGroupIndex", PagedIncenticeGroups);
}
Follwling ajax call is made for controller
function filterIncentiveGroup() {
var setIncentiveGroupStatus = $('input[name=IncentiveGroupStatus]:checked').val();
var Test = {
IncentiveGroupCode: $('#IncentiveGroupCode').val(),
IncentiveGroupName: $('#IncentiveGroupName').val(),
IncentiveGroupShortName: $('#IncentiveGroupShortName').val(),
IncentiveGroupStatus: setIncentiveGroupStatus,
};
$.ajax({
url: "/IncentiveGroup/Filter",
data: JSON.stringify(Test),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "html",
success: function (data) {
$('#myModal').modal('hide');
alert("Success");
},
error: function (errormessage) {
$('#myModal').modal('hide');
alert(errormessage.responseText);
}
});
};
Following is my IncentiveGroupIndex.cshtml
#using PagedList.Mvc
#model PagedList.IPagedList<MPISMVC.Models.IncentiveGroup>
#{
ViewBag.Title = "Incentive Group";
}
#*<h2>IncentiveGroupIndex</h2>*#
<div class="container-fluid" style="padding-top: 100px">
<div class="panel panel-primary">
<div class="panel-heading">Manage Incentive Group</div>
<div class="panel-body">
<div class="row">
<div class="col-md-4">
<button type="button" id="create" class="btn btn-success"><span class="glyphicon glyphicon-plus"></span>Add</button>
<button type="button" id="filter" class="btn btn-dafault"><span class="glyphicon glyphicon-filter"></span>Filter</button>
</div>
<div class="col-md-7">
<div class="pagination">
#* Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount *# #Html.PagedListPager(Model, page => Url.Action("IncentiveGroupIndex", new { page }), new PagedListRenderOptions { DisplayEllipsesWhenNotShowingAllPageNumbers = true, MaximumPageNumbersToDisplay = 5, LinkToFirstPageFormat = "First", LinkToPreviousPageFormat = "Previous", LinkToNextPageFormat = "Next", LinkToLastPageFormat = "Last" })
</div>
</div>
<div class="col-md-1">
#*#Html.DropDownList("PageSize", new SelectList(new Dictionary<string, int> { { "10", 10 }, { "20", 20 },{ "50", 50 }, { "100", 100 } }, "Key", "Value", Model.PageSize), new { #class = "form-control" })*#
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model[0].IncentiveGroupCode)
</th>
<th>
#Html.DisplayNameFor(model => model[0].IncentiveGroupName)
</th>
<th>
#Html.DisplayNameFor(model => model[0].IncentiveGroupShortName)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.IncentiveGroupCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.IncentiveGroupName)
</td>
<td>
#Html.DisplayFor(modelItem => item.IncentiveGroupShortName)
</td>
<td>
<button type="button" id="View" class="btn btn-sm btn-info" data-toggle="tooltip" title="View" onclick="details('#item.IncentiveGroupCode','View');"><span class="glyphicon glyphicon-eye-open"></span></button>
<button type="button" id="Edit" class="btn btn-sm btn-primary" data-toggle="tooltip" title="Edit" onclick="details('#item.IncentiveGroupCode','Edit');"><span class="glyphicon glyphicon-pencil"></span></button>
#*<button type="button" id="Delete" class="btn btn-sm btn-danger" data-toggle="tooltip" title="Delete" onclick="remove('#item.IncentiveGroupCode');"><span class="glyphicon glyphicon-trash"></span></button>*#
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
#* <div class="row">
<div class="pagination" style="margin-left: 400px">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount #Html.PagedListPager(Model, page => Url.Action("IncentiveGroupIndex", new { page }))
</div>
</div>*#
</div>
</div>
</div>
image of filtered data count
Related
I am programing a CRUD application. The add and edit do not want to work properly. For Adding, it shows me the successful message that the row is added, but nothing added in reality in my database. For Edit, I have a NullReferenceException after he tries to find the reclamation by his id :
StackTrace
In Debug mode, I can see that ng-model is doing his job, the add or edit modifications are take in account.
Here is my code :
reclamations-controller.js :
(function () {
'use strict';
angular
.module('app')
.controller('ReclamationsController', function ($scope, $http) {
$scope.Reclamations = [];
$scope.Reclamations.RecTitle = "";
$scope.Reclamations.RecDescription = "";
$scope.Reclamations.RecStatus = "";
$scope.Reclamations.RecResponsible = "";
$scope.Reclamations.RecComment = "";
// Popup variables
$scope.showModal = false;
$scope.buttonClicked = "";
$scope.toggleModal = function (btnClicked) {
$scope.buttonClicked = btnClicked;
$scope.showModal = !$scope.showModal;
};
// Export Data to Excel file
$scope.Export = function () {
$("#tblReclamations").table2excel({
filename: "Reclamations.xls",
exportOptions: {
columns: [1, 2]
}
});
}
$scope.showAddAndEditModal = false;
$scope.showAddAndEditModalFunction = function () {
if ($scope.showAddAndEditModal == false) {
$scope.showAddAndEditModal = true;
}
else {
$scope.showAddAndEditModal = false;
}
};
$scope.showImportModal = false;
$scope.showImportModalFunction = function () {
if ($scope.showImportModal == false) {
$scope.showImportModal = true;
}
else {
$scope.showImportModal = false;
}
};
// Add new reclamation function
$scope.InsertData = function () {
var Action = document.getElementById("btnSave").getAttribute("value");
if (Action == "Submit") {
$scope.Reclamations = [];
$scope.Reclamations.RecTitle = $scope.RecTitle;
$scope.Reclamations.RecDescription = $scope.RecDescription;
$scope.Reclamations.RecStatus = $scope.RecStatus;
$scope.Reclamations.RecResponsible = $scope.RecResponsible;
$scope.Reclamations.RecComment = $scope.RecComment;
$http({
method: "post",
url: "/Data/Insert_Reclamation",
datatype: "json",
data: JSON.stringify($scope.Reclamations)
}).then(function (response) {
alert(response.data);
$scope.GetAllData();
$scope.RecTitle = "";
$scope.RecDescription = "";
$scope.RecStatus = "";
$scope.RecResponsible = "";
$scope.RecComment = "";
})
} else {
$scope.Reclamations = [];
$scope.Reclamations.RecTitle = $scope.RecTitle;
$scope.Reclamations.RecDescription = $scope.RecDescription;
$scope.Reclamations.RecStatus = $scope.RecStatus;
$scope.Reclamations.RecResponsible = $scope.RecResponsible;
$scope.Reclamations.RecComment = $scope.RecComment;
$scope.Reclamations.RecId = document.getElementById("RecID_").value;
$http({
method: "post",
url: "/Data/Update_Reclamation",
datatype: "json",
data: JSON.stringify($scope.Reclamations)
}).then(function (response) {
alert(response.data);
$scope.GetAllData();
$scope.RecTitle = "";
$scope.RecDescription = "";
$scope.RecStatus = "";
$scope.RecResponsible = "";
$scope.RecComment = "";
document.getElementById("btnSave").setAttribute("value", "Submit");
document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";
document.getElementById("spn").innerHTML = "Add New Reclamation";
})
}
};
// Get all reclamations function
$scope.GetAllData = function () {
$http({
method: "get",
url: "/Data/Get_AllReclamation"
}).then(function (response) {
$scope.Reclamations = response.data;
}, function () {
alert("Error Occur");
})
};
// Delete function
$scope.DeleteReclamation = function (Rec) {
$http({
method: "POST",
url: "/Data/Delete_Reclamation",
datatype: "JSON",
data: JSON.stringify(Rec)
}).then(function (response) {
alert(response.data);
$scope.GetAllData();
})
};
// Update function
$scope.UpdateReclamation = function (Rec) {
document.getElementById("RecID_").value = Rec.RecId;
$scope.RecDate = new Date(Rec.RecDate);
$scope.RecTitle = Rec.RecTitle;
$scope.RecDescription = Rec.RecDescription;
$scope.RecStatus = Rec.RecStatus;
$scope.RecResponsible = Rec.RecResponsible;
$scope.RecComment = Rec.RecComment;
document.getElementById("btnSave").setAttribute("value", "Update");
document.getElementById("btnSave").style.backgroundColor = "Yellow";
document.getElementById("spn").innerHTML = "Update Reclamation Information";
};
});
})();
index.cshtml :
<p class="text-info text-center"><h3>Reclamations list</h3></p>
<div ng-app="app">
<div ng-controller="ReclamationsController" ng-init="GetAllData()" class="divList">
#*Reclamation Menu options*#
<div id="container" class="container">
<div class="row">
<input type="text" ng-model="searchFilter" placeholder="Search" />
<button ng-click="showAddAndEditModalFunction()" class="btn btn-primary a-btn-slide-
text">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
<span><strong>Add</strong></span>
</button>
<button class="btn btn-primary a-btn-slide-text" onclick="history.go(0);">
<span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>
<span>
<strong>Refresh</strong>
</span>
</button>
</div>
</div>
<br /><br /><br />
#* Reclamation table *#
<table id="tblReclamations" class="tableData" width="80" border="0" cellpadding="0"
cellspacing="0">
<thead>
<tr>
<th>Reclamation ID</th>
<th>Title</th>
<th>Description</th>
<th>Status</th>
<th>Responsible</th>
<th>Comment</th>
<th>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="Rec in Reclamations | filter: searchFilter" ng-class-odd="'odd'" ng-class-
even="'even'">
<td>{{Rec.RecId}}</td>
<td>{{Rec.RecTitle}}</td>
<td>{{Rec.RecDescription}}</td>
<td>{{Rec.RecStatus}}</td>
<td>{{Rec.RecResponsible}}</td>
<td>{{Rec.RecComment}}</td>
<td>
<button ng-click="UpdateReclamation(Rec); showAddAndEditModalFunction()"
class="btn btn-primary a-btn-slide-text">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
<span><strong>Edit</strong></span>
</button>
<a ng-click="DeleteReclamation(Rec)" class="btn btn-danger a-btn-slide-text">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Delete</strong></span>
</a>
</td>
</tr>
</tbody>
</table>
#* Add and edit part *#
<br /><br /><br /><br />
<div ng-show="showAddAndEditModal" class="form-horizontal" role="form">
<div class="container">
<div class="row">
<h2>
<span id="spn">Add New Reclamation</span>
</h2>
</div>
<div class="row">
#*<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Date :</label>
<div class="col-md-8">
<input type="date" class="form-control" id="inputDate" placeholder="Date"
ng-model="RecDate">
</div>
</div>
</div>*#
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Title :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputTitle"
placeholder="Title" ng-model="RecTitle">
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Description :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputDescription"
placeholder="Description" ng-model="RecDescription">
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Status :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputStatus"
placeholder="Status" ng-model="RecStatus">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Responsible :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputResponsible"
placeholder="Responsible" ng-model="RecResponsible">
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Comment :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputComment"
placeholder="Comment" ng-model="RecComment">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-lg-4">
<input type="button" id="btnSave" class="form-control btn-space" value="Submit"
ng-click="InsertData()" />
</div>
</div>
</div>
</div>
</div>
#Html.Hidden("RecID_")
</div>
#section scripts {
<script src="//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js">
</script>
<script src="~/Scripts/app/controllers/reclamations-controller.js"></script>
<script src="~/Scripts/app/controllers/import-controller.js"></script>
<script>
function refreshPage() {
window.location.reload();
}
</script>
}
DataController :
public JsonResult Get_AllReclamation ()
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
List<Reclamation> Rec = Obj.Reclamations.ToList();
return Json(Rec, JsonRequestBehavior.AllowGet);
}
}
public JsonResult Get_ReclamationById (string Id)
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
int RecId = int.Parse(Id);
return Json(Obj.Reclamations.Find(RecId), JsonRequestBehavior.AllowGet);
}
}
public string Insert_Reclamation (Reclamation Rec)
{
if (Rec != null)
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
if (ModelState.IsValid)
{
try
{
Obj.Reclamations.Add(Rec);
Obj.SaveChanges();
}
catch (DbEntityValidationException ex)
{
ErrorPrinter(ex.EntityValidationErrors);
}
catch (Exception ex)
{
Console.WriteLine("Exception not managed :");
Console.WriteLine(ex.Message);
}
}
return "Reclamation Added Successfully";
}
}
else
{
return "Reclamation Not Inserted! Try Again";
}
}
public string Update_Reclamation (Reclamation Rec)
{
if (Rec != null)
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
Reclamation RecObj = Obj.Reclamations.Where(a => a.RecId ==
Rec.RecId).FirstOrDefault();
RecObj.RecTitle = Rec.RecTitle;
RecObj.RecDescription = Rec.RecDescription;
RecObj.RecStatus = Rec.RecStatus;
RecObj.RecResponsible = Rec.RecResponsible;
RecObj.RecComment = Rec.RecComment;
Obj.SaveChanges();
return "Reclamation Updated Successfully";
}
}
else
{
return "Reclamation Not Updated! Try Again";
}
}
Thank you !
I have been trying to create a the ability to add/edit records through the use of a modal in .net core.
I have been trying tutorials such as
https://www.youtube.com/watch?v=QmNtbnUfns8
https://www.mindstick.com/Articles/12723/crud-operation-modal-popup-uses-bootstrap-in-mvc
Neither of these are working for as they are as .net. The modal isnt showing up.
ViewClients.cshtml
#model IEnumerable<Evol.Models.Clients>
#{
ViewData["Title"] = "Clients";
Layout = "~/Views/Shared/_Layout.cshtml";
<div class="card">
<div class="card-header card-header-text card-header-rose">
<div class="card-text">
<h4 class="card-title">Clients</h4>
<p class="card-category"></p>
</div>
</div>
<div class="card-body table-responsive">
<div class="table-responsive">
<table class="table table-hover" id="dataTable" width="100%" cellspacing="0">
<thead class="text-gray">
<tr>
<th>
#Html.DisplayNameFor(model => model.ClientName)
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(model => item.ClientName)
</td>
<td class="text-right">
<i class="material-icons">edit</i>
<button type="button" rel="tooltip" title="Remove" class="btn btn-
danger btn-link btn-sm">
<i class="material-icons">close</i>
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
<div class="modal fade" id="myModal1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">AddEdit Employee</h3>
</div>
<div class="modal-body" id="myModalBodyDiv1">
</div>
</div>
</div>
</div>
<script>
var EditClient = function (ClientID) {
var url = "/Client/EditClient?ClientID=" + ClientID;
$("#myModalBodyDiv1").load(url, function () {
$("#myModal1").modal("show");
})
}
EditClient.cshmtl (partial view)
#model Evol.Models.Clients
<form id="myForm">
#Html.HiddenFor(m => m.ClientID)
#Html.TextBoxFor(model => model.ClientName, new { #class = "form-control", #placeholder = "Name" })
<a href="#" id="btnSubmit" class="btn btn-success btn-block">
#if (Model.ClientID > 0)
{
<span>Update</span>
}
else
{
<span>Save</span>
}
</a>
</form>
Add Client
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
$("#loaderDiv").show();
var myformdata = $("#myForm").serialize();
alert("Success")
$.ajax({
type: "POST",
url: "/Client/ViewClients",
data: myformdata,
success: function () {
$("#loaderDiv").hide();
$("#myModal1").modal("hide");
}
})
})
})
ClientContoller
public IActionResult EditClient(int ClientID)
{
Clients client = new Clients();
if(ClientID > 0)
{
var user = _context.ClientTable.SingleOrDefault(x => x.ClientID == clientID);
client.ClientID = user.ClientID;
client.ClientName = user.ClientName;
}
return PartialView("EditClient", client);
}
}
Did You Created DbContext Class In Your Project?
CRUD Operations In ASP.NET Core Using Entity Framework Core Code First
EF Core DbContext Class Sample
below code just sample for show data and edit or add data to table.
[HttpGet]
public IActionResult AddEditCustomer(long? id)
{
CustomerViewModel model = new CustomerViewModel();
if (id.HasValue)
{
Customer customer = context.Set<Customer>().SingleOrDefault(c => c.Id == id.Value);
if (customer != null)
{
model.Id = customer.Id;
model.FirstName = customer.FirstName;
model.LastName = customer.LastName;
model.MobileNo = customer.MobileNo;
model.Email = customer.Email;
}
}
return PartialView("~/Views/Customer/_AddEditCustomer.cshtml", model);
}
[HttpPost]
public ActionResult AddEditCustomer(long? id, CustomerViewModel model)
{
try
{
if (ModelState.IsValid)
{
bool isNew = !id.HasValue;
Customer customer = isNew ? new Customer
{
AddedDate = DateTime.UtcNow
} : context.Set<Customer>().SingleOrDefault(s => s.Id == id.Value);
customer.FirstName = model.FirstName;
customer.LastName = model.LastName;
customer.MobileNo = model.MobileNo;
customer.Email = model.Email;
customer.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
customer.ModifiedDate = DateTime.UtcNow;
if (isNew)
{
context.Add(customer);
}
context.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("Index");
}
This is because you are missing the HTTP Post attribute PLEASE SEE the docs here
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1
[HTTPPOST]
public IActionResult EditClient(int ClientID)
{
Clients client = new Clients();
if(ClientID > 0)
{
var user = _context.ClientTable.SingleOrDefault(x => x.ClientID == clientID);
client.ClientID = user.ClientID;
client.ClientName = user.ClientName;
}
return PartialView("EditClient", client);
}
}
I made a HttpPost :
[HttpPost]
public IActionResult PokemonDetails(int PokemonId)
{
return PartialView("_PokemonDetails");
}
I want to find all the data from the Id in the http.
the datas are in my controller :
public IActionResult Index()
{
#region ListeDesPokemons
var pokemonList = new List<PokemonModel>();
var Id = 1;
var Img = 1;
pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Bulbizarre", UsName = "Bulbasaur(us)", JpName = "フシギダネ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Herbizarre", UsName = "Ivysaur(us)", JpName = "フシギソウ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
#endregion
var model = new PokemonViewModel();
model.Pokemons = pokemonList;
ViewBag.TotalPokemon1G = pokemonList.Count;
return View(model);
}
find good data from id thank you.
I do not have entity yet.
You could use TempData to pass data across different requests .TempData is used to pass data from current request to subsequent request (means redirecting from one page to another). It’s life is very short and lies only till the target view is fully loaded. But you can persist data in TempData by calling Keep() method.
Here is a simple working demo
Model:
public class PokemonModel
{
public int Id { get; set; }
public string Name { get; set; }
public string UsName { get; set; }
public string JpName { get; set; }
public string Type1 { get; set; }
public string Type2 { get; set; }
public int Rate { get; set; }
public string Image { get; set; }
}
public class PokemonViewModel
{
public List<PokemonModel> Pokemons { get; set; }
}
Controller:
public IActionResult PokemonList()
{
#region ListeDesPokemons
var pokemonList = new List<PokemonModel>();
var Id = 1;
var Img = 1;
pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Bulbizarre", UsName = "Bulbasaur(us)", JpName = "フシギダネ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Herbizarre", UsName = "Ivysaur(us)", JpName = "フシギソウ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
#endregion
var model = new PokemonViewModel();
model.Pokemons = pokemonList;
var json = JsonConvert.SerializeObject(pokemonList);
TempData["pokemonJson"] = json;
ViewBag.TotalPokemon1G = pokemonList.Count;
return View(model);
}
[HttpPost]
public IActionResult PokemonDetails(int PokemonId)
{
var pokemonJson = TempData["pokemonJson"].ToString();
TempData.Keep("pokemonJson");
var pokemonList = JsonConvert.DeserializeObject<List<PokemonModel>>(pokemonJson);
var pokemon = pokemonList.SingleOrDefault(p => p.Id == PokemonId);
return PartialView("_PokemonDetails",pokemon);
}
View:
#model WebApplication1.Models.PokemonViewModel
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Pokemons[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Pokemons[0].JpName)
</th>
<th>
#Html.DisplayNameFor(model => model.Pokemons[0].UsName)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Pokemons)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.JpName)
</td>
<td>
#Html.DisplayFor(modelItem => item.UsName)
</td>
<td>
<input hidden asp-for="#item.Id" />
PokemonDetails
</td>
</tr>
}
</tbody>
</table>
<div id="pokemon"></div>
#section Scripts{
<script type="text/javascript">
$(".btnclick").click(function () {
var id = $(this).closest("td").find("input").val();
$.ajax({
type: "post",
url: "/Home/PokemonDetails?PokemonId=" + id,
success: function (result) {
$("#pokemon").html(result);
}
});
});
</script>
}
PartialView
#model WebApplication1.Models.PokemonModel
<div>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.Id)
</dt>
<dd>
#Html.DisplayFor(model => model.Id)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
#Html.DisplayFor(model => model.Name)
</dd>
<dt>
#Html.DisplayNameFor(model => model.JpName)
</dt>
<dd>
#Html.DisplayFor(model => model.JpName)
</dd>
<dt>
#Html.DisplayNameFor(model => model.UsName)
</dt>
<dd>
#Html.DisplayFor(model => model.UsName)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Type1)
</dt>
<dd>
#Html.DisplayFor(model => model.Type1)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Type2)
</dt>
<dd>
#Html.DisplayFor(model => model.Type2)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Rate)
</dt>
<dd>
#Html.DisplayFor(model => model.Rate)
</dd>
</dl>
</div>
You can use LINQ to query the list for the Id you want.
int PokemonId = 2; // input from http post
var result = pokemonList.FirstOrDefault(p => p.Id == PokemonId);
Ok I made it here is the answer.
My controller:
public IActionResult Index()
{
#region ListeDesPokemons
var pokemonList = new List<PokemonModel>();
var Id = 1;
var Img = 1;
pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Bulbizarre", UsName = "Bulbasaur(us)", JpName = "フシギダネ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Herbizarre", UsName = "Ivysaur(us)", JpName = "フシギソウ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
var model = new PokemonViewModel();
model.Pokemons = pokemonList;
var json = JsonConvert.SerializeObject(pokemonList);
TempData["pokemonListJson"] = json;
TempData.Keep("PokemonListJson");
ViewBag.TotalPokemon1G = pokemonList.Count;
return View(model);
}
[HttpPost]
public IActionResult PokemonDetails(int pokemonId)
{
if (TempData["pokemonListJson"] != null)
{
if (string.IsNullOrEmpty(TempData["pokemonListJson"].ToString()))
{
return null;
}
}
var pokemonListJson = TempData["pokemonListJson"].ToString();
TempData.Keep("PokemonListJson");
var pokemonList = JsonConvert.DeserializeObject<List<PokemonModel>>(pokemonListJson);
var selectedPokemon = pokemonList.SingleOrDefault(p => p.Id == pokemonId);
if (selectedPokemon != null)
{
return PartialView("_PokemonDetails", selectedPokemon);
}
return null;
}
My partial View:
#model PokemonModel
<div id="taillDescriptionModal" class="modal-dialog modal-dialog-scrollable mw-100 m-auto" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 id="modalLabelStack2" class="modal-title font-weight-bold float-left">n° #Html.DisplayFor(model => model.Id)</h5>
<div id="nomPokemonStack2" class="ml-auto">
<h5 id="Name">#Html.DisplayFor(model => model.Name)</h5> <h5 id="UsName">#Html.DisplayFor(model => model.UsName)</h5> <h5 id="JpName">#Html.DisplayFor(model => model.JpName)</h5>
</div>
<button type="button" class="close" data-dismiss="modal" aria-label="close">
<span class="text-danger" aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col overflow-hidden">
<img class="img-fluid rounded-lg" src="#Html.DisplayFor(model => model.Image)" alt="pokemon.Name" />
</div>
<div class="col">
<span>Type : </span>
<div class="col text-white">
<span class="#Html.DisplayFor(model => model.Type1) badge">#Html.DisplayFor(model => model.Type1)</span>
<span class="#Html.DisplayFor(model => model.Type2) badge">#Html.DisplayFor(model => model.Type2)</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
<button type="submit" class="btn btn-success" onclick="afficheIdSurIndex(#Html.DisplayFor(model => model.Rate))"> Choisir</button>
</div>
</div>
</div>
<script>
function afficheIdSurIndex(selectedPokemonRate) {
$.ajax({
url: '/Pokedex/Calcul/',
type: 'POST',
dataType: "html",
data: { "selectedPokemonRate": selectedPokemonRate },
success: function () {
//enlever la classe pour afficher le contenu de la div
$('#Test').removeClass('text-hide');
//$('#Test').addClass('text-show');
var rateTxt = 'Taux de Capture du pokémon sélectionné : ' + selectedPokemonRate
//vider le contenu de la div
$("#Test").empty();
//écrire dans la div
$("#Test").append(rateTxt);
//fermer les modals
$('#pokemonDetails').modal('hide');
$('#choixPokemon').modal('hide');
}
})
}
</script>
My Index page:
#model PokemonViewModel
#{
ViewData["Title"] = "Pokedex";
Layout = "~/Views/Shared/_LayoutPokemon.cshtml";
<script src="~/lib/jquery/dist/jquery.min.js"></script>
}
<h1>Pokedex</h1>
<!-- Button choix Pokémon modal -->
<div class="container">
<button type="button" class="btn btn-primary mb-2" data-toggle="modal" data-target="#choixPokemon">
Pokemon 1G
</button>
</div>
<!-- Modal choix Pokémon -->
<div id="choixPokemon" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="choixPokemonModalLabel" aria-hidden="true">
<div id="modalWitdh" class="modal-dialog modal-dialog-scrollable mw-100 m-auto" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 id="choixPokemonModalLabel" class="modal-title">Pokédex première génération, #ViewBag.TotalPokemon1G Pokémons </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-center">
<div class="row">
#foreach (var pokemon in Model.Pokemons)
{
<div class="col">
<button type="submit" class="btn" onclick="getInfo(#pokemon.Id)">
<div class="card text-center rounded-lg">
<div id="tailleCard" class="card-body">
<h5 id="cardTitle" class="card-title">n°#pokemon.Id <br /> #pokemon.Name</h5>
<img id="tailleImg" src="#pokemon.Image" alt="#pokemon.Name" />
</div>
</div>
</button>
</div>
}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
</div>
</div>
</div>
</div>
<!-- Modal Description du pokémon choisi -->
<div id="pokemonDetails" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="descriptionPokemonModalLabel" aria-hidden="true">
#*Contenue dans vu partiel _PokemonDetails*#
</div>
#*Div de collection des donnés du pokémon selectionné dans le deuxième modal.(données provenant de la vue partiel _PokemonDetails) *#
<div class="row">
<div class="col">
<h6 id="Test" class="text-hide"></h6>
</div>
</div>
#*button script pour collecter les données du pokémon sélectionné dans le 1er modal*#
<script>
function getInfo(pokemonId) {
event.preventDefault;
console.log(pokemonId);
$.ajax({
url: '/Pokedex/PokemonDetails/',
type: 'POST',
dataType: "html",
data: { "pokemonId": pokemonId },
success: function (response) {
$("#pokemonDetails").html(response);
$('#pokemonDetails').modal('show');
}
})
}
</script>
In the startup page I need to add:
services.AddMemoryCache();
services.AddSession();
services.AddMvc().AddSessionStateTempDataProvider();
I put everything here for help anyone who need help.
add a breakpoint in action PokemonDetails:
[HttpPost]
public IActionResult PokemonDetails(int pokemonId)
{ // add break point here
when the break point is hit here, did you get pokemonId ?
I have a Layout page and a PartialView.
I have a search-button on the layout page and an update-button in a table in the partial view.
Once I click the search-button the update-button stops working. It works fine until I search. I'm guessing it has to do with the forms and actionresult but I can't get it to work. The actionresult is never reached - "nothing" happens.
Controller - RegisterTruckUser
[HttpPost]
public ActionResult RegisterTruckUser(string registerName, string registerPassword, string employeeNumber, string userTeam)
{
var model = new RegisterModel
{
UserList = db.SearchTruckUsers(""),
UserTeamList = GetUserTeamList(),
TriggerOnLoad = true
};
//If the Save button is clicked the user is updated
if (Request.Form.AllKeys.Contains("btnupdateuser"))
{
if (!Request["btnupdateuser"].IsEmpty())
{
Name = Request.Form["item.Name"];
password = Request["item.Password"];
EmployeeNumber = Request["item.EmployeeNumber"];
Userteam = Request["item.UserTeam"];
db.UpdateTruckUser(Name, password, EmployeeNumber, Userteam);
model.UserList = db.SearchTruckUsers("");
return PartialView(model);
}
}
ModelState.Clear();
return View(model);
}
model.TriggerOnLoadMessage = ErrorMessage;
return View(model);
}
Controller - SearchPartialView
[HttpPost]
public PartialViewResult SearchPartialView(string searchUserString)
{
if (Session["myID"] == null)
{
ExpireSession();
}
if (!ModelState.IsValid)
RedirectToLogin();
if (searchUserString.Any(char.IsDigit))
{
var model1 = new RegisterModel
{
TriggerOnLoad = false,
UserList = db.SearchTruckUsersEmpNum(searchUserString),
UserTeamList = GetUserTeamList()
};
return PartialView("_RegisterTruckUserPartialView", model1);
}
var model = new RegisterModel
{
TriggerOnLoad = false,
UserList = db.SearchTruckUsers(searchUserString),
UserTeamList = GetUserTeamList()
};
return PartialView("_RegisterTruckUserPartialView", model);
}
RegisterLayout
#model Name.Models.RegisterModel
<!DOCTYPE html>
<html lang="en">
<head>
<title>#ViewBag.Title - Register</title>
#Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
</head>
<body>
#RenderPage("~/Views/Shared/_Header.cshtml")
#RenderBody()
<div class="center" id="top">
<div id="search" class="active">
<h1>Manage users</h1>
#using (Ajax.BeginForm("SearchPartialView", "Register", null,
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "divUsers",
}, new
{
id = "usertable"
}))
{
#Html.TextBox("SearchUserString", null, new { #class = "responsivetextbox", #placeholder = "Search username or employment number" })
<p>
<input type="submit" class="standardbutton logsearch" name="submit" value="Search" />
</p>
}
<div id="divUsers">
#{Html.RenderPartial("_RegisterTruckUserPartialView");}
</div>
</div>
</div>
#RenderPage("~/Views/Shared/_Footer.cshtml")
</body>
</html>
PartialView (table)
<table class="centeredTable">
<thead>
<tr>
<th>Name</th>
<th>Password</th>
<th>Employment Number</th>
<th>Team</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.UserList)
{
using (Html.BeginForm())
{
<tr id="usertabletr1">
<td id="usertabletd1">
#Html.EditorFor(modelItem => item.Name, new {htmlAttributes = new {#name = "test1", #style = "border: 0px none;"}})
</td>
<td id="usertabletd1">
#Html.EditorFor(modelItem => item.Password, new {htmlAttributes = new {#name = "registerPassword", #type = "password", #style = "border: 0px none; "}})
</td>
<td id="usertabletd1">
#Html.EditorFor(modelItem => item.EmployeeNumber, new {htmlAttributes = new {#name = "employeeNumber", #readonly = "readonly", #style = "border: 0px none; background: white;"}})
</td>
<td id="usertabletd1">
#Html.DropDownListFor(modelItem => item.UserTeam, Model.UserTeamList, item.UserTeam, new {htmlAttributes = new {#name = "Team", #style = "border: 0px none;"}})
</td>
<td id="usertabletd1">
<input class="standardbutton adddefaultvaluesubmit" type="image" src="~/Pictures/saveicon.ico" alt="Save" value="Save" name="btnupdateuser"/>
<input class="standardbutton adddefaultvaluesubmit" type="image" src="~/Pictures/trashcanicon.ico" alt="Delete" value="Delete" name="btndeleteuser"/>
</td>
</tr>
}
}
</tbody>
</table>
In your partial view it should look something like this.
<input type="button" value="Confirm team change" class="btnConfirm"/>
And then you add this to your "main" layout.
$(document).on('click', '.btnConfirm', function(){
$.ajax({
url: '#Url.Action("RegisterTruckUser", "Register")',
type: 'POST',
cache: false,
async: true,
data: $('form').serialize(),
success: function(result){
//do something
}
});
});
I have an Index page with various filtering options on it, all included within a PagedList. They all appear to be working fine, except for the dates.
When I first filter by date, they work fine however when I click on a page number at the bottom, the search criteria for my date is disappearing.
I can see that I can passing the search term in the paged list, and I can see this date hit my controller and the filtering happen but the ViewBag.filterStartDate and ViewBag.filterEndDate just aren't binding back to my textboxes for some reason.
Index.cshtml:
#using PagedList.Mvc
#model PagedList.IPagedList<Job>
#using (Html.BeginForm("Index", "Jobs", FormMethod.Get, new { #class = "form-inline", role = "form" }))
{
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Filter Search Results</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item">
#Html.Label("By Id: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterId", ViewBag.filterId as string, new { #class = "form-control" })
</li>
<li class="list-group-item">
#Html.Label("By Address Line 1: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterAddress1", ViewBag.filterAddress1 as string, new { #class = "form-control" })
</li>
<li class="list-group-item">
#Html.Label("By Username: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterUsername", ViewBag.filterUsername as string, new { #class = "form-control" })
</li>
<li class="list-group-item">
#Html.Label("By Contract: ", new { #class = "col-md-4 control-label" })
#Html.DropDownList("filterContract", null, "-- Select One --",
new { #class = "form-control" })
</li>
<li class="list-group-item">
#Html.Label("Date Created Start: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterStartDate", ViewBag.filterStartDate as string, new { #class = "form-control date", type = "date" })
</li>
<li class="list-group-item">
#Html.Label("Date Created End: ", new { #class = "col-md-4 control-label" })
#Html.TextBox("filterFinishDate", ViewBag.filterFinishDate as string, new { #class = "form-control date", type = "date" })
</li>
<li class="list-group-item">
#Html.Label("By App: ", new { #class = "col-md-4 control-label" })
#Html.DropDownList("filterApp", null, "-- Select One --",
new { #class = "form-control" })
</li>
</ul>
<input type="submit" value="Apply Filter" class="btn btn-default" />
</div>
<div id="items" style="padding: 15px;">
#Html.Partial("Jobs", Model)
</div>
</div>
}
Jobs.cshtml:
#using System.Web.UI.WebControls
#using PagedList.Mvc
#model PagedList.IPagedList<Job>
#Html.ActionLink("Create New", "Create", null, new { #style = "float: left" })
#Html.ActionLink("Import Jobs", "Import", null, new { #style = "padding-left: 15px" })
#Html.ValidationSummary(true)
<table class="table">
<tr>
<th class="mobileview">
#Html.DisplayName("JobId")
</th>
<th>
#Html.DisplayName("Description")
</th>
<th class="mobileview">
#Html.DisplayName("Address")
</th>
<th class="mobileview">
#Html.DisplayName("Priority")
</th>
<th>
#Html.DisplayName("Date Created")
</th>
<th>
#Html.DisplayName("Username")
</th>
</tr>
#foreach (var item in Model)
{
<tr class="formrow">
<td class="mobileview">
#Html.DisplayFor(modelItem => item.JobId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td class="mobileview">
#Html.DisplayFor(modelItem => item.Address1)
</td>
<td class="mobileview">
#Html.DisplayFor(modelItem => item.Priority)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateCreated)
</td>
<td>
#Html.DisplayFor(modelItem => item.User.UserName)
</td>
<td class="mobileview">
#Html.ActionLink("View Job", "Details", new { id = item.JobId })
</td>
<td class="mobileview">
#if (item.Data != null)
{
#Html.ActionLink("View Data", "Details", "AppForms", new { id = item.Data.Id }, null)
}
else
{
#Html.DisplayFor(modelItem => item.Status)
}
</td>
</tr>
}
</table>
<p>Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount</p>
#Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, filterAddress1 = ViewBag.filterAddress1, filterId = ViewBag.filterId, filterUsername = ViewBag.filterUsername, filterStartDate = ViewBag.filterStartDate, filterFinishDate = ViewBag.filterFinishDate, filterApp = ViewBag.selectedApp, filterContract = ViewBag.selectedContract }), PagedListRenderOptions.Classic)
JobsController.cs:
public ActionResult Index(string sortOrder, string currentFilter, string filterId, string filterAddress1, int? page, String filterApp, String filterContract, DateTime? filterStartDate, DateTime? filterFinishDate, String filterUsername)
{
//...Other filtering
//Filter by date
if (filterStartDate != null)
{
jobs = jobs.Where(x => x.DateCreated >= filterStartDate);
//ViewBag.filterStartDate = filterStartDate.Value.Year + "-" + filterStartDate.Value.Month + "-" + filterStartDate.Value.Day;
ViewBag.filterStartDate = filterStartDate;
}
if (filterFinishDate != null)
{
//Make sure we're checking to the end of the end date (ie 01/01/2015 23:59:59)
filterFinishDate = filterFinishDate.Value.AddHours(23).AddMinutes(59).AddSeconds(59);
jobs = jobs.Where(x => x.DateCreated <= filterFinishDate);
//ViewBag.filterFinishDate = filterFinishDate.Value.Year + "-" + filterFinishDate.Value.Month + "-" + filterFinishDate.Value.Day;
ViewBag.filterFinishDate = filterFinishDate;
}
int pageSize = int.Parse(ConfigurationManager.AppSettings["MaxPageItemCount"]);
int pageNumber = page ?? 1;
return this.View(jobs.ToPagedList(pageNumber, pageSize));
}
#Html.TextBox() can pull values out of the ModelState or ViewData.
Try building the html for the date input manually like this:
<input type="date" name="filterStartDate" id="filterStartDate" class="form-control date" value="#ViewBag.filterStartDate.ToString("yyyy-MM-dd")"/>
Resolved the issue by manually creating the date inputs rather tahn relying on Razor to do it for me!
#if (ViewBag.filterStartDate != null)
{
<input type="date" name="filterStartDate" id="filterStartDate" value="#ViewBag.filterStartDate.ToString("yyyy-MM-dd")" />
}
else
{
<input type="date" name="filterStartDate" id="filterStartDate" value="" />
}