I have a problem, I dont get send my data to another page, basically
I need click on date-item link and pass data to another page form filled with data from the first page:
#model List<PontoWeb.Models.Ponto>
#{
ViewBag.Title = "Relatório de Ponto";
ViewBag.MesAtual = System.DateTime.Now.Month;
}
<h2>#ViewBag.Title</h2>
<div class="container-fluid">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Marcar Ponto", "MarcarPonto")</li>
<li>#Html.ActionLink("Ir para Mês Anterior", "MostraPontoMesAnterior",new { ViewBag.MesAgora})</li>
<li>#Html.ActionLink("Ir para Próximo Mês", "MostraPontoMesFuturo", new { ViewBag.MesAgora })</li>
</ul>
</div>
</div>
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>Data</th>
<!-- <th>Dia da Semana</th> -->
<th>Entrada</th>
<th>Saída Almoço</th>
<th>Entrada Almoço</th>
<th>Saída</th>
<th>Saldo Diário</th>
<th>Saldo Acumulado</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#Html.ActionLink(item.Data, "MarcarPonto", new { data = item.Data, #entrada = item.Entrada, saida_almoco = item.Saida_Almoco, entrada_almoco = item.Entrada_Almoco, saida = item.Saida }) </td>
<td>#item.Entrada </td>
<td>#item.Saida_Almoco</td>
<td>#item.Entrada_Almoco </td>
<td>#item.Saida</td>
<td>#item.Saldo_Dia</td>
<td>#item.Saldo_Acumulado</td>
</tr>
}
</tbody>
</table>
</div>
to This page
#{
ViewBag.Title = "Marcar Ponto";
}
<div class="container">
<h2>Marcador de Ponto Diário</h2>
<div class="container-fluid">
<div class="row">
<ul>
<li>#Html.ActionLink("Ir para Ponto", "MostraPonto")</li>
</ul>
</div>
</div>
<form class="form" action="/Ponto/Marcar">
<div class="form-group">
<label for="data">Data:</label>
<input type="date" class="form-control" id="data" name="data" value="data">
</div>
<div class="form-group">
<label for="entrada">Entrada:</label>
<input type="time" class="form-control" id="entrada" name="entrada" value="00:00" max="23:59">
</div>
<div class="form-group">
<label for="saida_almoco">Saída Almoço:</label>
<input type="time" class="form-control" id="saida_almoco" name="saida_almoco" value="00:00" max="23:59">
</div>
<div class="form-group">
<label for="entrada_almoco">Entrada Almoço:</label>
<input type="time" class="form-control" id="entrada_almoco" name="entrada_almoco" value="00:00" max="23:59">
</div>
<div class="form-group">
<label for="saida">Saída:</label>
<input type="time" class="form-control" id="saida" name="saida" value="00:00" max="23:59">
</div>
<button type="submit" class="btn btn-default">Gravar</button>
</form>
</div>
<script>
document.getElementById('data').valueAsDate = new Date();
</script>
My controller:
using PontoWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PontoWeb.Controllers
{
public class PontoController : Controller
{
// GET: Ponto
public ActionResult Index()
{
return View();
}
public ActionResult MostraPonto() {
Operacoes operacoes = new Operacoes();
int MesCorrente= DateTime.Now.Month;
ViewBag.MesAgora = MesCorrente;
return View(operacoes.Select(MesCorrente));
}
public ActionResult MarcarPonto() {
return View();
}
// [Route("MarcarPonto/{data}")]
public ActionResult MarcarPontoDados(string data, DateTime entrada, DateTime saida_almoco, DateTime entrada_almoco, DateTime saida)
{
Operacoes op = new Operacoes();
ViewBag.Ponto.Data = op.SelectData(data);
//ViewBag.Ponto.Data = data;
//ViewBag.Ponto.Entrada = entrada;
//ViewBag.Ponto.Saida_Almoco = saida_almoco;
//ViewBag.Ponto.Entrada_Almoco = entrada_almoco;
//ViewBag.Ponto.Saida = saida;
return View("MarcarPonto");
}
public ActionResult Marcar( string data, DateTime entrada, DateTime saida_almoco, DateTime entrada_almoco, DateTime saida ) {
Ponto ponto = new Ponto();
ponto.Data = data ;
ponto.Entrada = entrada.Hour.ToString("00.##") + ":" + entrada.Minute.ToString("00.##");
ponto.Saida_Almoco = saida_almoco.Hour.ToString("00.##") + ":" + saida_almoco.Minute.ToString("00.##");
ponto.Entrada_Almoco = entrada_almoco.Hour.ToString("00.##") + ":" + entrada_almoco.Minute.ToString("00.##");
ponto.Saida = saida.Hour.ToString("00.##") + ":" + saida.Minute.ToString("00.##");
Operacoes operacoes = new Operacoes();
operacoes.Add(ponto);
return Redirect("MostraPonto");
}
public ActionResult MostraPontoMesAnterior(int MesAgora) {
Operacoes operacoes = new Operacoes();
int MesAnterior = MesAgora - 1;
ViewBag.MesAgora = MesAnterior;
return View("MostraPonto",operacoes.Select(MesAnterior));
}
public ActionResult MostraPontoMesFuturo(int MesAgora)
{
Operacoes operacoes = new Operacoes();
int MesFuturo = MesAgora + 1;
ViewBag.MesAgora = MesFuturo;
return View("MostraPonto", operacoes.Select(MesFuturo));
}
}
}
I need get from page1
<td>#Html.ActionLink(item.Data, "MarcarPonto", new { data = item.Data, #entrada = item.Entrada, saida_almoco = item.Saida_Almoco, entrada_almoco = item.Entrada_Almoco, saida = item.Saida }) </td>
To page2 filled.
x-x-x-x-x-x-x-x-x--x-x-x-x-x-x-x-x-x-x-x--x-x
x-x-x-x-x-x-x-x-x--x-x-x-x-x-x-x-x-x-x-x--x-x
x-x-x-x-x-x-x-x-x--x-x-x-x-x-x-x-x-x-x-x--x-x
x-x-x-x-x-x-x-x-x--x-x-x-x-x-x-x-x-x-x-x--x-x
Related
I have in one view two submit buttons
The First one search for users in Active directory
The Second one Add selected user to table AspNetUsers
I have specified username which is staff id in button attribute asp-route-id so that I can add that specific user from the list of users that will appear after clicking the search button. but the problem is that it add the first person in the list. it doesn't add the one I clicked on.
This is my controller
[AcceptVerbs("Get", "Post")]
public async Task<IActionResult> AddUser(SearchViewModel profile , string button, List<User> users )
{
if (button == "Search")
{
if (ModelState.IsValid)
{
users = new List<User>();
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain.com"))
{
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.DisplayName = profile.Name + "*";
using (PrincipalSearcher srch = new PrincipalSearcher(qbeUser))
{
if (!string.IsNullOrEmpty(srch.FindAll().ToString()))
{
foreach (var found in srch.FindAll())
{
if (found != null)
{
users.Add(new User()
{
Name = found.Name,
Email = found.UserPrincipalName,
SatffID = found.SamAccountName
});
}
else
{
return View();
}
}
SearchViewModel returnmodel = new SearchViewModel(users);
return View(returnmodel);
}
}
}
}
}
if(button=="Add")
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = profile.ID, Email = profile.Email, DisplayName = profile.DisplayName };
var result = await userManager.CreateAsync(user);
if (result.Succeeded)
{
if(profile.Location !=null)
{
for (int i = 0; i < profile.Location.Count; i++)
{
var newUser = await userManager.FindByNameAsync(profile.ID);
var userId = newUser.Id;
//var newUser = profile.ID;
UserLocation userLoc = new UserLocation
{
UserID = userId.ToString(),
LocID = profile.Location[i]
};
userLocation.Add(userLoc);
}
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError(string.Empty, "No locs");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
ModelState.AddModelError(string.Empty, "");
}
return View(profile);
}
return View(profile);
}
This is my View AddUser
#model SearchViewModel
<h1>Add New User</h1>
#Html.ValidationSummary(true)
<form method="post" formaction="">
<div id="content">
<fieldset>
<div class="form-group col-md-12">
#Html.LabelFor(model => Model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(modelItem => Model.Name, new { htmlAttributes = new { #class = "form-control", #style = "width:280px" }, })
</div>
<div>
<div class="form-group row">
<label asp-for="#Model.Location" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<select asp-for="#Model.Location" asp-items="Html.GetEnumSelectList<Location>()" class="custom-select mr-sm-2" id="Subjects_dropdown" multiple>
<option value="">Please Select</option>
</select>
<span asp-validation-for="#Model.Location" class="text-danger"></span>
</div>
</div>
</div>
<div class="col-md-2">
<input type="submit" class="btn btn-default" name="button" value="Search">
</div>
<div class="col-md-3">
</div>
</div>
</fieldset>
<br>
</div>
<table id="historyTable" class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Staff Id</th>
<th>Add User</th>
</tr>
</thead>
<tbody>
#if (Model.FoundUsers != null)
{
#foreach (var user in Model.FoundUsers)
{
if (user != null)
{
<tr>
<td><label asp-for="DisplayName"></label><input asp-for="DisplayName" value="#user.Name" name="displayname" /></td>
<td><label asp-for="Email"></label><input asp-for="Email" value="#user.Email" name="Email" /></td>
<td><label asp-for="ID"></label><input asp-for="ID" value="#user.SatffID" name="ID" /></td>
<td><input type="submit" class="btn btn-primary" name="button" value="Add" asp-route-Id="#user.SatffID" asp-action="AddUser"></td>
</tr>
}
}
}
else
{
<tr>
<td colspan="4">No Record Available</td>
</tr>
}
</tbody>
</table>
</form>
}
#section Scripts{
<script>
$(document).ready(function () {
$('#Subjects_dropdown').multiselect();
});
</script>
}
I try to reproduce your issue in my side, and I found that if I click Add button, the request contains all rows data like screenshot below:
So I think the issue comes from the form submit, I tried to add form for each row, and it worked.
Here's my code snippet, just adding #using (Html.BeginForm()) for content。
Here's a similar question as yours, and you can also refer to it to write js script to achieve it.
My controller action:
[AcceptVerbs("Get", "Post")]
public IActionResult AddUser(SearchViewModel profile, string button, List<User> users)
{
ViewData["Location"] = new List<string> {
"location_a",
"location_b"
};
if (button == "Search")
{
if (ModelState.IsValid)
{
users = new List<User>();
users.Add(new User()
{
Name = "name_a",
Email = "email_a",
SatffID = "staff_a"
});
users.Add(
new User()
{
Name = "name_b",
Email = "email_b",
SatffID = "staff_b"
});
users.Add(
new User()
{
Name = "name_c",
Email = "email_c",
SatffID = "staff_c"
});
SearchViewModel returnmodel = new SearchViewModel();
returnmodel.FoundUsers = users;
return View(returnmodel);
}
}
if (button == "Add")
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = profile.ID, Email = profile.Email, DisplayName = profile.DisplayName };
//save data
return RedirectToAction("Index", "Home");
}
return View(profile);
}
return View(profile);
}
View code :
#model SearchViewModel
<h1>Add New User</h1>
#Html.ValidationSummary(true)
<form method="post" formaction="">
<div id="content">
<fieldset>
<div class="form-group col-md-12">
#Html.LabelFor(model => Model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(modelItem => Model.Name, new { htmlAttributes = new { #class = "form-control", #style = "width:280px" }, })
</div>
<div>
<div class="form-group row">
<label asp-for="#Model.Location" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<select asp-for="#Model.Location" asp-items="(#ViewData["Location"] as IEnumerable<SelectListItem>)" class="custom-select mr-sm-2" id="Subjects_dropdown" multiple>
<option value="">Please Select</option>
</select>
<span asp-validation-for="#Model.Location" class="text-danger"></span>
</div>
</div>
</div>
<div class="col-md-2">
<input type="submit" class="btn btn-default" name="button" value="Search">
</div>
<div class="col-md-3">
</div>
</div>
</fieldset>
<br>
</div>
<table id="historyTable" class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Staff Id</th>
<th>Add User</th>
</tr>
</thead>
<tbody>
#if (Model.FoundUsers != null)
{
#foreach (var user in Model.FoundUsers)
{
if (user != null)
{
<tr>
#using (Html.BeginForm())
{
<td><label asp-for="DisplayName"></label><input asp-for="DisplayName" value="#user.Name" name="displayname" /></td>
<td><label asp-for="Email"></label><input asp-for="Email" value="#user.Email" name="Email" /></td>
<td><label asp-for="ID"></label><input asp-for="ID" value="#user.SatffID" name="ID" /></td>
<td><input type="submit" class="btn btn-primary" name="button" value="Add" asp-route-Id="#user.SatffID" asp-action="AddUser"></td>
}
</tr>
}
}
}
else
{
<tr>
<td colspan="4">No Record Available</td>
</tr>
}
</tbody>
</table>
</form>
#section Scripts{
<script>
$(document).ready(function () {
$('#Subjects_dropdown').multiselect();
});
</script>
}
This is what related code I only added
I have the following application, where I have to upload an image directly from modal to the page.
Note that:
The image is already uploaded by the admin to this modal.
The images are saved in "static" file in "wwwroot" folder. So, No database is required for this step.
All what I need is when I click in the image in the modal, it should be uploaded to the view. So, I can save it later in the database.
Here is Image Bank Controller
public IActionResult Index()
{
var webRoot = _hostingEnvironment.WebRootPath;
var appData = System.IO.Path.Combine(webRoot, "static");
var files = Directory.GetFiles(appData, "*.*", SearchOption.AllDirectories);
var model = new ImageBankViewModel()
{
ImagesListUrls = files.Select(i=>Path.GetFileName(i))
};
return View(model);
}
[HttpPost]
public IActionResult Upload(ImageBankViewModel model)
{
if (ModelState.IsValid)
{
if (model.Image != null)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "static");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var extension = Path.GetExtension(model.Image.FileName);
var newFileName = model.Type + "-" + DateTime.Now.Ticks;
using (var filesStream = new FileStream(Path.Combine(path, newFileName + extension), FileMode.Create))
{
model.Image.CopyTo(filesStream);
}
return RedirectToAction("Index");
}
}
ImageBankViewModel modelVM = new ImageBankViewModel()
{
Image = model.Image,
ImagesListUrls = model.ImagesListUrls,
Type = model.Type
};
return RedirectToAction("Index",modelVM);//Unsuccessful Upload , fix invalid model
}
public IActionResult CreateStory()
{
return View();
}
public ActionResult GetImagesPartial()
{
var webRoot = _hostingEnvironment.WebRootPath;
var appData = System.IO.Path.Combine(webRoot, "static");
var files = Directory.GetFiles(appData, "*.*", SearchOption.AllDirectories);
var model = new ImageBankViewModel()
{
ImagesListUrls = files.Select(i => Path.GetFileName(i))
};
return PartialView("_ImagesBankModal",model);
}
public void ImageDelete(string image)
{
}
public void SelectImage(string image)
{
// Here I want to get the selected image from the modal
}
}
}
Create Story View
#{
ViewData["Title"] = "CreateStory";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>CreateStory</h1>
<div class="row">
<div class="col-md-1">
<label>Pic1</label>
</div>
<div class="col-md-8">
<input type="file" accept="image/*" class="form-control" />
</div>
<div class="col-md-3">
<a class="btn btn-outline-dark" asp-area="" asp-controller="Bank" asp-action="GetImagesPartial" data-toggle="modal" data-target="#myModal" id="sel">Select from image bank</a>
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="partial"></div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-1">
<label>Pic2</label>
</div>
<div class="col-md-8">
<input type="file" accept="image/*" class="form-control" />
</div>
<div class="col-md-3">
<button class="btn btn-outline-dark">Select from image bank</button>
</div>
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$('#sel').click(function () {
var route = '#Url.Action("GetImagesPartial", "Bank")';
$('#partial').load(route);
});
});
</script>
}
Modal Partial View
#model TestApplication.Models.ViewModels.ImageBankViewModel
<div class="modal-header">
<h2 class="modal-title">Choose</h2>
</div>
<div class="modal-body">
#if (Model.ImagesListUrls.Any())
{
<table>
#foreach (var image in Model.ImagesListUrls)
{
<tr>
<td>
<a asp-area="" asp-controller="Bank" asp-action="SelectImage" asp-route-image="#image" class="btn btn-light position-absolute" style="right:0">Select</a>
<img src="~/static/#image" class="img-thumbnail" />
</td>
</tr>
}
</table>
}
else
{
<h5>no images exists...</h5>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Cancel</button>
</div>
You can store the relative path of the selected picture in an input and pass them to the action.
The following is an example, you can refer to it.
Index
<form asp-action="Upload" asp-controller="ImageBank" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-1">
<label>Pic1</label>
</div>
<div class="col-md-8">
<input type="file" accept="image/*" class="form-control" name="model.Image"/>
<ul class="selectedpic">
</ul>
</div>
<div class="col-md-3">
<a class="btn btn-outline-dark sel">Select from image bank</a>
</div>
<div class="col-md-8 addedimg">
</div>
</div>
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="partial"></div>
</div>
</div>
</div>
<button type="submit">submit</button>
</form>
#section Scripts{
<script type="text/javascript">
var currentsel="";
$('body').on("click",".sel",function () {
localStorage.setItem("currentsel",$(this).attr("class"));
var route = '#Url.Action("GetImagesPartial", "ImageBank")';
$("#myModal").modal("show");
$('#partial').load(route);
});
$('body').on("click",".selectbtn",function () {
var currenttd=$(this).closest("td");
console.log(currenttd.find("img").attr("src"))
var classarry=localStorage.getItem("currentsel").split(" ");
var currentsel="."+classarry[classarry.length-1];
var currentaddedimg=$(currentsel).closest(".row").find(".addedimg");
var addsrc=currenttd.find("img").attr("src");
if(checkisexsist(currentaddedimg,addsrc)){
$(currentsel).closest(".row").find(".selectedpic").append("<li>"+addsrc+"</li>");
$(currentsel).closest(".row").find(".addedimg").append("<input hidden name='selimages' value='"+addsrc+"'/>");
$("#myModal").modal("hide");
$('#myModal').on('hidden.bs.modal', function (e) {
localStorage.removeItem("currentsel");
});
}else{
alert("has selected");
}
});
function checkisexsist(currentaddedimg,addsrc){
var flag=true;
$.each(currentaddedimg.find("input[name='selimages']"), function( index, value ) {
if($(value).val()==addsrc){
flag=false;
}
});
return flag;
}
</script>
}
Controller
[HttpPost]
public IActionResult Upload(ImageBankViewModel model,List<string> selimages)
{
if (ModelState.IsValid)
{
if (model.Image != null)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var path =Path.Combine(webRootPath, "static");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var extension = Path.GetExtension(model.Image.FileName);
var newFileName = model.Type + "-" + DateTime.Now.Ticks;
using (var filesStream = new FileStream(Path.Combine(path, newFileName + extension), FileMode.Create))
{
model.Image.CopyTo(filesStream);
}
}
if(selimages!=null& selimages.Count != 0)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "static");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
selimages.ForEach(m =>
{
var newFileName = Guid.NewGuid().ToString();
var extension = "." + m.Split(".")[m.Split(".").Length - 1];
var oldpath =webRootPath+m.Replace("/", "\\"); var newpath = Path.Combine(path, newFileName + extension);
System.IO.File.Copy(oldpath,newpath);
});
}
return RedirectToAction("Index");
}
ImageBankViewModel modelVM = new ImageBankViewModel()
{
Image = model.Image,
ImagesListUrls = model.ImagesListUrls,
Type = model.Type
};
return RedirectToAction("Index", modelVM);//Unsuccessful Upload , fix invalid model
}
_ImagesBankModal(Only give the modified place)
<a class="btn btn-light position-absolute selectbtn">Select</a>
Result
I have problem regarding showing correct time in IndexPage. When I create Patient I want to be display DateTime, currently It is only represent Date but in Index Page I get time.
What I try so far is to add DataAnnotation in my Model something like:
public class AdmissionPacients
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Date and Time")]
//[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
//[DataType(DataType.Date)]
public DateTime DateAndTime { get; set; }
[Required]
[Display(Name = "Emergency Admission")]
public bool Emergency { get; set; }
public string Image { get; set; }
// Doctor
[Display(Name = "Doctor Name")]
public int DoctorId { get; set; }
[ForeignKey("DoctorId")]
public virtual Doctor Doctor { get; set; }
//Patient
[Display(Name = "Patient Name")]
public int PatientId { get; set; }
[ForeignKey("PatientId")]
public virtual Patient Patient { get; set; }
}
Create.cshtml
#model BergClinics.Models.ViewModel.AdmisionVM
#{
ViewData["Title"] = "Upsert";
var title = "Create Admission Patient";
}
<form method="post" enctype="multipart/form-data">
#if (Model.AdmissionPatient.Id != 0)
{
<input asp-for="AdmissionPatient.Id" hidden />
title = "Edit Admission Patient";
}
<div class="border p-3">
<div class="form-group row">
<h2 class="text-info pl-3">#title</h2>
</div>
<div class="row">
<div class="col-8">
<div class="form-group row py-2">
<div class="col-4">
<label>Doctor Full Name : </label>
</div>
<div class="col-8">
<select asp-for="AdmissionPatient.DoctorId" asp-items="#Model.DoctorSelectList" class="form-control">
<option disabled selected>--Select Docotor--</option>
</select>
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Patient Full Name: </label>
</div>
<div class="col-8">
<select asp-for="AdmissionPatient.PatientId" asp-items="#Model.PatientSelectList" class="form-control">
<option disabled selected>--Select Patient--</option>
</select>
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Date and Time :</label>
</div>
<div class="col-8">
<input asp-for="AdmissionPatient.DateAndTime" type="text" class="form-control datepicker">
</div>
</div>
#*<div class="form-group row py-2">
<div class="col-4">
<label asp-for="AdmissionPatient.DateAndTime"></label>
</div>
<div class="col-8">
<input asp-for="AdmissionPatient.DateAndTime" class="form-control datepicker" />
<span asp-validation-for="AdmissionPatient.DateAndTime" class="text-danger"></span>
</div>
</div>*#
<div class="form-group row py-2">
<div class="col-4">
<label>Patient Image :</label>
</div>
<div class="col-3">
<input type="file" name="files" id="imageBox" multiple class="form-control" />
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Emergency reception :</label>
</div>
<div class="col-8">
<input asp-for="AdmissionPatient.Emergency" type="checkbox" class="form-control" id="emergencyId">
<label class="form-check-label" for="exampleCheck1"></label>
</div>
</div>
<div class="form-group row py-2">
<div class="col-8 offset-4 row">
<div class="col">
#if (Model.AdmissionPatient.Id != 0)
{
//update
<input type="submit" class="btn btn-info w-100" value="Update" />
}
else
{
//create
<input type="submit" onclick="return validateInput()" class="btn btn-primary w-100" value="Create" />
}
</div>
</div>
</div>
</div>
<div class="col-4">
#if (Model.AdmissionPatient.Id != 0)
{
<img src="#Constans.imagePath#Model.AdmissionPatient.Image" width="100%" style="border-radius:5px; border:1px solid #bbb" />
}
</div>
</div>
</div>
</form>
#section Scripts{
#{
<partial name="_ValidationScriptsPartial" />
}
<script src="~/js/admissionPatient.js"></script>
}
Index
<div class="container p-3 bg-white">
<div class="row pt-4">
<div class="col-6">
<h2 class="text-primary">Admission Patient List</h2>
</div>
<div class="col-6 text-right">
<a asp-action="Upsert" class="btn btn-primary">
<i class="fas fa-plus"></i> Create New Doctor
</a>
</div>
</div>
<br /><br />
#*<form asp-action="Index">
<p>
Date From: <input type="datetime" name="search" />
Date To: <input type="datetime" name="search">
<input type="submit" value="Search" />
</p>
</form>*#
#if (Model.Count() > 0)
{
<table id="tblData" class="table table-striped border" style="width:100%">
<thead>
<tr class="table-dark">
<th>
Doctor Full Name - CODE
</th>
<th>
Patient Full Name
</th>
<th>
Date and Time
</th>
<th>
Emergency
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var obj in Model)
{
<tr>
<td width="25%">#obj.Doctor.Firstname #obj.Doctor.Lastname #obj.Doctor.Code</td>
<td width="25%">#obj.Patient.FirstName #obj.Patient.LastName</td>
<td width="25%">#obj.DateAndTime</td>
#if (obj.Emergency == true)
{
<td width="25%" class="blink_me"><span class="blink_me">Emergency</span></td>
}
else
{
<td width="25%"><span class="text-info">#obj.Emergency</span></td>
}
<td class="text-center">
<div class="w-75 btn-group" role="group">
<a asp-route-Id="#obj.Id" asp-action="Upsert" class="btn btn-primary mx-2">
<i class="fas fa-edit"></i>
</a>
<a asp-route-Id="#obj.Id" asp-action="Delete" class="btn btn-danger mx-2">
<i class="far fa-trash-alt"></i>
</a>
</div>
</td>
</tr>
}
</tbody>
</table>
}
else
{
<p> No Admission Patient exists.</p>
}
</div>
#section Scripts{
<script src="~/js/admissionPatient.js"></script>
}
Controller
public class AdmissionPatientController : Controller
{
private readonly ApplicationDbContext _db;
private readonly IWebHostEnvironment _webHostEnvironment;
public AdmissionPatientController(ApplicationDbContext db, IWebHostEnvironment webHostEnvironment)
{
_db = db;
_webHostEnvironment = webHostEnvironment;
}
public IActionResult Index(string search)
{
IEnumerable<AdmissionPacients> admissionPatient = _db.AdmissionPacients
.Include(u => u.Patient)
.Include(d => d.Doctor);
if (!string.IsNullOrEmpty(search))
{
if (DateTime.TryParse(search, out var dateTime))
{
admissionPatient = admissionPatient.Where
(x => x.DateAndTime.ToShortDateString().Equals(dateTime.ToShortDateString())).ToList();
}
}
return View(admissionPatient);
}
//UPSERT GET
//UPdate and insERT
public IActionResult Upsert(int? Id)
{
AdmisionVM admissionVM = new AdmisionVM
{
AdmissionPatient = new AdmissionPacients(),
PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
}),
DoctorSelectList = _db.Doctors.Select(i => new SelectListItem
{
Text = i.Firstname + i.Lastname,
Value = i.Id.ToString()
})
};
AdmissionPacients admissionPatient = new AdmissionPacients();
if (Id == null)
{
// this is for create
return View(admissionVM);
}
else
{
// this is for edit
admissionVM.AdmissionPatient = _db.AdmissionPacients.Find(Id);
if (admissionVM.AdmissionPatient == null)
{
return NotFound();
}
return View(admissionVM);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upsert(AdmisionVM admissionVM)
{
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
string webRootPath = _webHostEnvironment.WebRootPath;
if (admissionVM.AdmissionPatient.Id == 0)
{
//Creating
string upload = webRootPath + Constans.imagePath;
string fileName = Guid.NewGuid().ToString();
string extension = Path.GetExtension(files[0].FileName);
using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create))
{
files[0].CopyTo(fileStream);
}
admissionVM.AdmissionPatient.Image = fileName + extension;
_db.AdmissionPacients.Add(admissionVM.AdmissionPatient);
}
else
{
//Updating
var objFromDb = _db.AdmissionPacients.AsNoTracking().FirstOrDefault(u => u.Id == admissionVM.AdmissionPatient.Id);
if (files.Count > 0)
{
string upload = webRootPath + Constans.imagePath;
string fileName = Guid.NewGuid().ToString();
string extension = Path.GetExtension(files[0].FileName);
var oldFile = Path.Combine(upload, objFromDb.Image);
if (System.IO.File.Exists(oldFile))
{
System.IO.File.Delete(oldFile);
}
using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create))
{
files[0].CopyTo(fileStream);
}
admissionVM.AdmissionPatient.Image = fileName + extension;
}
else
{
admissionVM.AdmissionPatient.Image = objFromDb.Image;
}
_db.AdmissionPacients.Update(admissionVM.AdmissionPatient);
}
_db.SaveChanges();
return RedirectToAction("Index");
}
admissionVM.PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
});
admissionVM.DoctorSelectList = _db.Doctors.Select(i => new SelectListItem
{
Text = i.Firstname + i.Lastname,
Value = i.Id.ToString()
});
return View(admissionVM);
}
//GET - DELETE
public IActionResult Delete(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
AdmissionPacients admissionPatient = _db.AdmissionPacients
.Include(u => u.Patient)
.Include(d => d.Doctor)
.FirstOrDefault(u => u.Id == id);
if (admissionPatient == null)
{
return NotFound();
}
return View(admissionPatient);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteAdmission(int? Id)
{
var obj = _db.AdmissionPacients.Find(Id);
if (obj == null)
{
return NotFound();
}
string upload = _webHostEnvironment.WebRootPath + Constans.imagePath;
var oldfile = Path.Combine(upload, obj.Image);
if (System.IO.File.Exists(oldfile))
{
System.IO.File.Delete(oldfile);
}
_db.AdmissionPacients.Remove(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
Nothing works!
So I want as user to be able to select DateTime and this DateTime needs to be represent in IndexPage
Anyone know where did I make mistake ? What I made wrong here ?
I think you should use DateTime.ToString() formatting. There are many formats of datetimes are available in C# . Please check the link => DateTime Formatting Link
DateTime DateAndTime = new DateTime(2020, 5, 29, 5, 50, 0);
DateAndTime.ToString("dddd, dd MMMM yyyy");//Output:Friday, 29 May 2020 05:50
DateAndTime.ToString("dddd, dd MMMM yyyy");//Output:Friday, 29 May 2020 05:50 AM
DateAndTime.ToString("dddd, dd MMMM yyyy");//Output:Friday, 29 May 2020 5:50
DateAndTime.ToString("dddd, dd MMMM yyyy");//Output:Friday, 29 May 2020 5:50 AM
DateAndTime.ToString("dddd, dd MMMM yyyy HH:mm:ss");//Output:Friday, 29 May 2020 05:50:06
DateAndTime.ToString("MM/dd/yyyy HH:mm");//Output:05/29/2020 05:50
DateAndTime.ToString("MM/dd/yyyy hh:mm tt");//Output:05/29/2020 05:50 AM
DateAndTime.ToString("MM/dd/yyyy H:mm");//Output:05/29/2020 5:50
DateAndTime.ToString("MM/dd/yyyy h:mm tt");//Output:05/29/2020 5:50 AM
DateAndTime.ToString("MM/dd/yyyy HH:mm:ss");//Output:05/29/2020 05:50:06
Note: Here Outputs are dummy data output. Please check your code with "ToString" and let me know.
OR
You can use Annotation too like=>
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-ddTHH:mm:ss}")]`
OR
You can also check that link to on stackoverflow. Link
I am making a MVC web app where one form affects many tables in the database. I have the page loading info into the Entity Framework, but I get a duplicate entity error when I run db.SaveChanges(). The database is completely empty so it has to be some error with the Save.
I suspect it has something to do with how I am uploading the data to the Framework, but I cannot figure out the correct way to do it.
Here is the Model:
public class BOGOModel
{
public BOGOModel()
{
}
public string PROMOTION_CODE { get; set; }
public string DESCRIPTION { get; set; }
public DateTime START_DATE_TIME { get; set; }
public DateTime END_DATE_TIME { get; set; }
public int[] BUY_MEMBERS { get; set; }
public int[] GET_MEMBERS { get; set; }
public int PERCENT_OFF { get; set; }
}
Here is the Controller:
public ActionResult BOGO()
{
return View();
}
[HttpPost]
public JsonResult BOGOSave(string MemberData)
{
BOGOModel ModelData = JsonConvert.DeserializeObject<BOGOModel>(MemberData);
PROMOTION Promotion = new PROMOTION();
Promotion.PROMOTION_CODE = ModelData.PROMOTION_CODE;
Promotion.DESCRIPTION = ModelData.DESCRIPTION;
Promotion.PROMOTION_TYPESysID = 12001;
Promotion.PROMOTION_APPLY_ASSysID = 98401;
Promotion.START_DATE_TIME = ModelData.START_DATE_TIME.ToString();
Promotion.END_DATE_TIME = ModelData.END_DATE_TIME.ToString();
db.PROMOTIONs.Add(Promotion);
AT_PROMOTION_ORG_UNIT PromotionOrgUnit = new AT_PROMOTION_ORG_UNIT();
PromotionOrgUnit.ORG_UNIT = "150";
PromotionOrgUnit.ORG_UNIT_TYPE = "Outlet";
PromotionOrgUnit.PARENT_ORG_UNIT = "DG";
db.AT_PROMOTION_ORG_UNIT.Add(PromotionOrgUnit);
ALLOCATED_ORG_UNIT AllocatedOrgUnit = new ALLOCATED_ORG_UNIT();
AllocatedOrgUnit.AT_PROMOTION_ORG_UNIT = PromotionOrgUnit;
db.ALLOCATED_ORG_UNIT.Add(AllocatedOrgUnit);
MP_PROMOTION__ALLOCATED_ORG_UNIT Map_P_A = new MP_PROMOTION__ALLOCATED_ORG_UNIT();
Map_P_A.PROMOTION = Promotion;
Map_P_A.ALLOCATED_ORG_UNIT = AllocatedOrgUnit;
db.MP_PROMOTION__ALLOCATED_ORG_UNIT.Add(Map_P_A);
PROMOTION_RULE BuyRule = new PROMOTION_RULE();
BuyRule.TARGET_TYPESysID = 1;
BuyRule.TARGET = 1;
db.PROMOTION_RULE.Add(BuyRule);
AT_PROMOTION_SET BuySetAttributes = new AT_PROMOTION_SET();
BuySetAttributes.name = "Buy";
BuySetAttributes.type = "BENEFIT";
BuySetAttributes.PROMOTION_SELECTIONSysID = 1;
db.AT_PROMOTION_SET.Add(BuySetAttributes);
PROMOTION_SET BuySet = new PROMOTION_SET();
BuySet.AT_PROMOTION_SET = BuySetAttributes;
db.PROMOTION_SET.Add(BuySet);
foreach(int upc in ModelData.BUY_MEMBERS)
{
AT_PROMOTION_MEMBER_KEY_VALUE MemberValue = new AT_PROMOTION_MEMBER_KEY_VALUE();
MemberValue.KEY_VALUE = upc;
db.AT_PROMOTION_MEMBER_KEY_VALUE.Add(MemberValue);
PROMOTION_MEMBER Member = new PROMOTION_MEMBER();
Member.LK_KEY_TYPE = db.LK_KEY_TYPE.Where(Type => Type.KEY_TYPESysID == 1).First();
Member.AT_PROMOTION_MEMBER_KEY_VALUE = MemberValue;
db.PROMOTION_MEMBER.Add(Member);
MP_PROMOTION_SET__PROMOTION_MEMBER Map_S_M = new MP_PROMOTION_SET__PROMOTION_MEMBER();
Map_S_M.PROMOTION_SET = BuySet;
Map_S_M.PROMOTION_MEMBER = Member;
db.MP_PROMOTION_SET__PROMOTION_MEMBER.Add(Map_S_M);
}
PROMOTION_RULE GetRule = new PROMOTION_RULE();
GetRule.TARGET_TYPESysID = 1;
GetRule.TARGET = 1;
GetRule.BENEFIT_TYPESysID = 5;
GetRule.BENEFIT = ModelData.PERCENT_OFF;
db.PROMOTION_RULE.Add(GetRule);
AT_PROMOTION_SET GetSetAttributes = new AT_PROMOTION_SET();
GetSetAttributes.name = "Get";
GetSetAttributes.type = "TARGET";
GetSetAttributes.PROMOTION_SELECTIONSysID = 1;
db.AT_PROMOTION_SET.Add(GetSetAttributes);
PROMOTION_SET GetSet = new PROMOTION_SET();
GetSet.AT_PROMOTION_SET = GetSetAttributes;
db.PROMOTION_SET.Add(GetSet);
foreach (int upc in ModelData.GET_MEMBERS)
{
AT_PROMOTION_MEMBER_KEY_VALUE MemberValue = new AT_PROMOTION_MEMBER_KEY_VALUE();
MemberValue.KEY_VALUE = upc;
db.AT_PROMOTION_MEMBER_KEY_VALUE.Add(MemberValue);
PROMOTION_MEMBER Member = new PROMOTION_MEMBER();
Member.LK_KEY_TYPE = db.LK_KEY_TYPE.Where(Type => Type.KEY_TYPESysID == 1).First();
Member.AT_PROMOTION_MEMBER_KEY_VALUE = MemberValue;
db.PROMOTION_MEMBER.Add(Member);
MP_PROMOTION_SET__PROMOTION_MEMBER Map_S_M = new MP_PROMOTION_SET__PROMOTION_MEMBER();
Map_S_M.PROMOTION_SET = GetSet;
Map_S_M.PROMOTION_MEMBER = Member;
db.MP_PROMOTION_SET__PROMOTION_MEMBER.Add(Map_S_M);
}
MP_PROMOTION__PROMOTION_SET Buy_Map_P_S = new MP_PROMOTION__PROMOTION_SET();
Buy_Map_P_S.PROMOTION = Promotion;
Buy_Map_P_S.PROMOTION_SET = BuySet;
db.MP_PROMOTION__PROMOTION_SET.Add(Buy_Map_P_S);
MP_PROMOTION__PROMOTION_SET Get_Map_P_S = new MP_PROMOTION__PROMOTION_SET();
Get_Map_P_S.PROMOTION = Promotion;
Get_Map_P_S.PROMOTION_SET = GetSet;
db.MP_PROMOTION__PROMOTION_SET.Add(Get_Map_P_S);
db.SaveChanges();
return Json("success");
}
Here is the View:
#model Promotion_Generator.Models.BOGOModel
#{
ViewBag.Title = "Buy One Get One";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2><b>Buy One Get One Free</b></h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<p class = "control-label col-md-2"><b>Promotion Code</b></p>
<div class="col-md-10 PC">
<input type="text" name="f-Promotion-Code" class="form-control f-Promotion-Code01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Description</b></p>
<div class="col-md-10 Desc">
<input type="text" name="f-Description" class="form-control f-Description01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Start Date Time</b></p>
<div class="col-md-10 SDT">
<input type="datetime" name="f-Start-Date-Time" class="form-control f-Start-Date-Time01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>End Date Time</b></p>
<div class="col-md-10 EDT">
<input type="datetime" name="f-End-Date-Time" class="form-control f-End-Date-Time01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Percent Off</b></p>
<div class="col-md-10 PO">
<input type="number" name="f-Percent-Off" class="form-control f-Percent-Off01" />
</div>
</div>
<div class="form-group col-md-10">
<h3><b>Buy Products</b></h3>
<table class="table" id="buytable">
<thead>
<tr>
<th>Product UPC</th>
<th />
<th />
</tr>
</thead>
<tbody>
<tr class="data-buy">
<td>
<input type="number" name="f-upc" class="form-control f-upc01" />
</td>
</tr>
</tbody>
</table>
<button type="button" id="btnAdd" class="btn btn-primary btn-md pull-right btn-sm classBuyAdd">Add More</button>
</div>
<div class="form-group col-md-10">
<h3><b>Get Products</b></h3>
<table class="table" id="gettable">
<thead>
<tr>
<th>Product UPC</th>
<th />
<th />
</tr>
</thead>
<tbody>
<tr class="data-get">
<td>
<input type="number" name="f-upc" class="form-control f-upc01" />
</td>
</tr>
</tbody>
</table>
<button type="button" id="btnAdd" class="btn btn-primary btn-md pull-right btn-sm classGetAdd">Add More</button>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" id="btnSubmit" value="Submit" class="btn btn-default">Submit</button>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to Home", "Index", "Home")
</div>
#section scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".classBuyAdd", function () {
var rowCount = $('.data-contact-person').length + 1;
var contactdiv = '<tr class="data-buy">' +
'<td><input type="number" name="f-upc' + rowCount + '" class="form-control f-upc01" /></td>' +
'<td><button type="button" id="btnDelete" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
'</tr>';
$('#buytable').append(contactdiv);
});
});
$(document).ready(function () {
$(document).on("click", ".classGetAdd", function () {
var rowCount = $('.data-contact-person').length + 1;
var contactdiv = '<tr class="data-get">' +
'<td><input type="number" name="f-upc' + rowCount + '" class="form-control f-upc01" /></td>' +
'<td><button type="button" id="btnDelete" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
'</tr>';
$('#gettable').append(contactdiv);
});
});
$(document).on("click", ".deleteContact", function () {
$(this).closest("tr").remove();
});
function getAllData() {
var data = [];
$('div.PC').each(function () {
var upc = $(this).find('.f-Promotion-Code01').val();
data.push(upc);
});
$('div.Desc').each(function () {
var upc = $(this).find('.f-Description01').val();
data.push(upc);
});
$('div.SDT').each(function () {
var upc = $(this).find('.f-Start-Date-Time01').val();
data.push(upc);
});
$('div.EDT').each(function () {
var upc = $(this).find('.f-End-Date-Time01').val();
data.push(upc);
});
var UPC1 = []
$('tr.data-buy').each(function () {
var upc = $(this).find('.f-upc01').val();
UPC1.push(upc);
});
var UPC2 = [];
$('tr.data-get').each(function () {
var upc = $(this).find('.f-upc01').val();
UPC2.push(upc);
});
$('div.PO').each(function () {
var upc = $(this).find('.f-Percent-Off01').val();
data.push(upc);
});
var alldata = {
'PROMOTION_CODE': data[0],
'DESCRIPTION': data[1],
'START_DATE_TIME': data[2],
'END_DATE_TIME': data[3],
'BUY_MEMBERS': UPC1,
'GET_MEMBERS': UPC2,
'PERCENT_OFF': data[4],
}
console.log(alldata);
return alldata;
}
$("#btnSubmit").click(function () {
var data = JSON.stringify(getAllData());
console.log(data);
$.ajax({
url: 'BOGOSave',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'MemberData': data }),
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});
});
</script>
}
Any help would be appreciated. Thanks!
Edit 1: Here is the specific error message:
{"Violation of PRIMARY KEY constraint 'PK__AT_PROMO__36BD5C21B6ADDCDF'. Cannot insert duplicate key in object 'dbo.AT_PROMOTION_MEMBER_KEY_VALUE'. The duplicate key value is (0).\r\nThe statement has been terminated."}
The schema is way to large to fit in this post, but here is the table mentioned in the error:
CREATE TABLE [AT_PROMOTION_MEMBER_KEY_VALUE] (
[PROMOTION_MEMBER_KEY_VALUESysID] int PRIMARY KEY NOT NULL,
[KEY_VALUE] bigint NOT NULL,
[sku] varchar(MAX) NULL,
[owner] varchar(10) NULL,
[owner_type] int FOREIGN KEY REFERENCES [LK_OWNER_TYPE] ([OWNER_TYPESysID]) NULL,
[product_group_type] varchar(10) NULL
);
OK, I fixed the problem. It turns out that I didn't auto increment the primary key and since I wasn't manually setting it either it was always 0. Even though there wasn't anything in the database it still couldn't insert because I was trying to create two items and they had the same ID. Thanks to the comments that helped to figure this out.
I've been struggling for far too long with this now, and I think I've finally found where the problem is!
I am making a review section in an Asp.Net Core web app, I have added 2 drop downs that filter reviews by product, and set the number of reviews per page.
For the paged list I am using Sakura.AspNetCore.PagedList.
I am trying to use ajax to return the partial view which has the filtered and sorted reviews, and all goes well, until the model is passed back. At first I couldn't figure it out, then using chrome, I found a 500 error, and from there found the following error in the resonse:
InvalidOperationException: The model item passed into the ViewDataDictionary is of Microsoft.AspNetCore.Mvc.PartialViewResult but this ViewDataDictionary instance requires a model item of type Sakura.AspNetCore.IPagedList
I can't for the life of me figure out how to fix this, the model although a pagedlist is a partialView... here's the offending part of the code in my model:
public async Task<ActionResult> ShowReviewDetails(string searchProduct, int? page, string perPage)
{
// get product via id
var prodId = Convert.ToInt32(searchProduct);
var prod = await _context.Product.FindAsync(prodId);
searchProduct = prod.ProductName;
if (perPage == "0")
{
perPage = _context.Product.Count().ToString();
}
var perPageGet = Convert.ToInt32(perPage);
if (perPageGet <= 0)
{
perPageGet = _context.Product.Count();
}
int pageSize = Convert.ToInt32(perPageGet);
int pageNumber = (page ?? 1);
IEnumerable<Review> reviews = await _context.Review.Where(r => r.ReviewApproved == true).ToListAsync();
if (!string.IsNullOrWhiteSpace(searchProduct) || !string.IsNullOrEmpty(searchProduct))
{
searchProduct = StringExtensions.UppercaseFirst(searchProduct);
}
if (!string.IsNullOrEmpty(searchProduct) || !string.IsNullOrWhiteSpace(searchProduct) || searchProduct == "0")
{
page = 1;
reviews = await _context.Review.Where(r => r.Product == searchProduct && r.ReviewApproved == true).ToListAsync();
}
if (searchProduct == "All" || string.IsNullOrEmpty(searchProduct))
{
reviews = await _context.Review.Where(r => r.ReviewApproved == true).ToListAsync();
}
reviews = reviews.ToPagedList(pageSize, pageNumber);
return PartialView(reviews);
I'm still fairly green when it comes to asp.net core and c#, so any help or suggestions would be welcomed, maybe there is a better option for paging?
Thanks for your time!
EDIT: added views and script
My partial view parent:
#{
ViewBag.Title = "Review Dashboard";
#using YaCu_2017.Controllers;
}
<p class="green-text">#ViewBag.StatusMessage</p>
<p class="red-text">#ViewBag.ErrorMessage</p>
<h2>Our Product Reviews</h2>
<div class="reviewView" id="filter">
#await Html.PartialAsync("ShowReviewDetails")
</div>
The actual partialview:
#model IPagedList<YaCu_2017.Models.Review>
#using System.Globalization
#using Sakura.AspNetCore
#using YaCu_2017.Controllers
#using YaCu_2017.Models
#{
ViewData["Title"] = "Digital Jeeves - Reviews";
}
<div class="row">
<div class="col s2">
<h5>Filter by Product:</h5>
<form method="get" >
#{
var product = ReviewController.GetProductListIncId();
var productCount = ReviewController.GetProductCountList();
ViewBag.ProductList = product;
ViewBag.ProductCount = productCount;
}
<select asp-items="#ViewBag.ProductList" id="searchProduct" class="dropdown-button btn"></select>
<h5>Reviews per page</h5>
<select asp-items="#ViewBag.ProductCount" id="perPage" class="dropdown-button btn"></select>
</form>
</div>
</div>
<div class="row">
<div class="col s12 center center-align center-block">
<p>Page #(Model.TotalPage < Model.PageIndex ? 1 : Model.PageIndex) of #Model.TotalPage<pager class="pagination" setting-link-attr-data-ajax="true" /></></p>
</div>
</div>
<hr />
<div>
#foreach (var item in Model)
{
var stars = Convert.ToDouble(item.Stars);
<div class="container opaque-parent z-depth-5">
<div class="row">
<div class="col s6"><h6 style="border-bottom:thin">Title : #Html.DisplayFor(model => item.Title)</h6></div>
<div class="col s3"><h6 style="border-bottom:thin">Product : #Html.DisplayFor(model => item.Product)</h6></div>
<div class="col s3"><h6 style="border-bottom:thin">Rated: <ej-rating value="#stars" id="#item.Id" read-only="true" /></h6></div>
</div>
<div class="row" style="">
<div class="col s12" style="border-bottom:inset">
<h6>Comment:</h6>
</div>
</div>
<div class="row" style="border-bottom:inset">
<div class="col s6 offset-s3">
<p class="flow-text">"#Html.DisplayFor(model => item.ReviewText)"</p>
</div>
</div>
<div class="row">
<div class="col s3">
<p>Date Created : #Html.DisplayFor(modelItem => item.CreatedDate)</p>
</div>
<div class="col s3">
<p>Chosen Display Name: #Html.DisplayFor(modelItem => item.DisplayName)</p>
</div>
</div>
</div>
<hr />
}
</div>
<div class="row">
<div class="col s12 center center-align center-block">
<p>Page #(Model.TotalPage < Model.PageIndex ? 1 : Model.PageIndex) of #Model.TotalPage<pager class="pagination" setting-link-attr-data-ajax="true" /></></p>
</div>
</div>
and my document ready function:
$("#searchProduct").change(function () {
var product = $("#searchProduct").val();
var perPage = $("#perPage").val();
$("#filter").load('http://LocalHost:50426/Review/GetProducts?searchProduct=' + product + '&perPage=' + perPage);
});
$("#perPage").change(function () {
var product = $("#searchProduct").val();
var perPage = $("#perPage").val();
$("#filter").load('http://LocalHost:50426/Review/GetProducts?searchProduct=' + product + '&perPage=' + perPage);
});
The answer was stupidly simple, I kicked my self so hard I won't be sitting down for a week!
I just needed to return partialView(GetReviewDetails) as IPagedList.
For the sake of completness (Is that even a word?) here is everything as it ended up!
Views:
Modified index (Parent) as I was duplicating an entire page lol:
#model Sakura.AspNetCore.IPagedList<YaCu_2017.Models.Review>
#{
ViewBag.Title = "Review Dashboard";
#using YaCu_2017.Controllers;
}
<p class="green-text">#ViewBag.StatusMessage</p>
<p class="red-text">#ViewBag.ErrorMessage</p>
<h2>Our Product Reviews</h2>
<div class="row">
<div class="col s2">
<h5>Filter by Product:</h5>
<form method="get">
#{
var product = ReviewController.GetProductListIncId();
var productCount = ReviewController.GetProductCountList();
ViewBag.ProductList = product;
ViewBag.ProductCount = productCount;
}
<select asp-items="#ViewBag.ProductList" id="searchProduct" class="dropdown-button btn"></select>
<h5>Reviews per page</h5>
<select asp-items="#ViewBag.ProductCount" id="perPage" class="dropdown-button btn"></select>
</form>
</div>
</div>
<div class="row">
<div class="col s12 center center-align center-block">
<p>Page #(Model.TotalPage < Model.PageIndex ? 1 : Model.PageIndex) of #Model.TotalPage<pager class="pagination" setting-link-attr-data-ajax="true" /></></p>
</div>
</div>
<hr />
<div>
<div class="reviewView" id="filter">
#await Html.PartialAsync("ShowReviewDetails", Model)
</div>
</div>
<div class="row">
<div class="col s12 center center-align center-block">
<p>Page #(Model.TotalPage < Model.PageIndex ? 1 : Model.PageIndex) of #Model.TotalPage<pager class="pagination" setting-link-attr-data-ajax="true" /></></p>
</div>
</div>
Modified ShowReviewDetails (Child / partial) only has the loop:
#model IPagedList<YaCu_2017.Models.Review>
#using System.Globalization
#using Sakura.AspNetCore
#using YaCu_2017.Controllers
#using YaCu_2017.Models
#{
ViewData["Title"] = "Digital Jeeves - Reviews";
}
#foreach (var item in Model)
{
var stars = Convert.ToDouble(item.Stars);
<div class="container opaque-parent z-depth-5">
<div class="row">
<div class="col s6"><h6 style="border-bottom:thin">Title : #Html.DisplayFor(model => item.Title)</h6></div>
<div class="col s3"><h6 style="border-bottom:thin">Product : #Html.DisplayFor(model => item.Product)</h6></div>
<div class="col s3"><h6 style="border-bottom:thin">Rated: <ej-rating value="#stars" id="#item.Id" read-only="true" /></h6></div>
</div>
<div class="row" style="">
<div class="col s12" style="border-bottom:inset">
<h6>Comment:</h6>
</div>
</div>
<div class="row" style="border-bottom:inset">
<div class="col s6 offset-s3">
<p class="flow-text">"#Html.DisplayFor(model => item.ReviewText)"</p>
</div>
</div>
<div class="row">
<div class="col s3">
<p>Date Created : #Html.DisplayFor(modelItem => item.CreatedDate)</p>
</div>
<div class="col s3">
<p>Chosen Display Name: #Html.DisplayFor(modelItem => item.DisplayName)</p>
</div>
</div>
</div>
<hr />
}
Now the controllers:
I have a GetProducts() controller, which is uses to load the partial via ajax and is where I needed to add as IPagedList:
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> GetProducts(string searchProduct, int? page, string perPage)
{
var product = int.Parse(searchProduct);
var obj = await this.ShowReviewDetails(searchProduct, page, perPage) as IPagedList;
return PartialView("ShowReviewDetails", obj);
}
The index control:
public async Task<ActionResult> Index(Review model, string sortOrder, string searchString, string searchProduct, int? page, string perPage)
{
await ShowReviewDetails(model, sortOrder, searchString, searchProduct, page, perPage);
return View();
}
And finally ShowReviewDetails:
public async Task<ActionResult> ShowReviewDetails(string searchProduct, int? page, string perPage)
{
// get product via id
var prodId = Convert.ToInt32(searchProduct);
if (prodId > 0)
{
var dbProd = await _context.Product.FindAsync(prodId);
var prod = new Product()
{
Id = dbProd.Id,
ProductName = dbProd.ProductName,
Cost = dbProd.Cost,
ProductCategory = dbProd.ProductCategory,
ProductDescription = dbProd.ProductDescription,
};
searchProduct = prod.ProductName;
}
else
{
searchProduct = "All";
}
if (perPage == "0")
{
perPage = _context.Product.Count().ToString();
}
var perPageGet = Convert.ToInt32(perPage);
if (perPageGet <= 0)
{
perPageGet = _context.Product.Count();
}
int pageSize = Convert.ToInt32(perPageGet);
int pageNumber = (page ?? 1);
IEnumerable<Review> reviews = await _context.Review.Where(r => r.ReviewApproved == true).ToListAsync();
if (!string.IsNullOrWhiteSpace(searchProduct) || !string.IsNullOrEmpty(searchProduct))
{
searchProduct = StringExtensions.UppercaseFirst(searchProduct);
}
if (!string.IsNullOrEmpty(searchProduct) || !string.IsNullOrWhiteSpace(searchProduct) || searchProduct == "0")
{
page = 1;
reviews = await _context.Review.Where(r => r.Product == searchProduct && r.ReviewApproved == true).ToListAsync();
}
if (searchProduct == "All" || string.IsNullOrEmpty(searchProduct))
{
reviews = await _context.Review.Where(r => r.ReviewApproved == true).ToListAsync();
}
reviews = reviews.ToPagedList(pageSize, pageNumber);
return PartialView(reviews);
}