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
Related
I'm creating a web site, where I have a list of classes, and I want that each class will have it`s own calendar. What I mean is, when I click button 1, I will go to a separate calendar then button 2 and so on.
I already have a working calendar, I just don't understand how assign to each button a calendar.
So I have a working calendar with options of add/delete/update events, but I don't understand how to connect them.
I'm on this problem over a week now, and I couldn't find any solution. help please.
This is the index.cshtml where the classes are created: (classes view)
#model IEnumerable<ClasSaver.Models.ClassesModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<style>
.button {
background-color: deepskyblue; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Building)
</th>
<th>
#Html.DisplayNameFor(model => model.How_Many_In_Class)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Building)
</td>
<td>
#Html.DisplayFor(modelItem => item.How_Many_In_Class)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
<input id="#item.Id" type="button" onclick="parent.open('https://www.google.com/')" value="Open in new window" class="button">
</td>
</tr>
}
</table>
<script>
</script>
and the controller
using ClasSaver.Data;
using ClasSaver.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ClasSaver.Controllers
{
public class ClassesController : Controller
{
// GET: Classes
public ActionResult Index()
{
List<ClassesModel> classes = new List<ClassesModel>();
ClassDAO classDao = new ClassDAO();
classes = classDao.FetchAll();
return View("Index",classes);
}
public ActionResult Details(int id)
{
ClassDAO classesDAO = new ClassDAO();
ClassesModel classes = classesDAO.FetchOne(id);
return View("Details", classes);
}
public ActionResult Create(ClassesModel classesModel)
{
return View("ClassesForm", classesModel);
}
[HttpPost]
public ActionResult ProcessCreate(ClassesModel classesModel)
{
//save to DB
ClassDAO classesDAO = new ClassDAO();
classesDAO.CreateOrUpdate(classesModel);
return View("Details", classesModel);
}
public ActionResult Edit(int id)
{
ClassDAO classesDAO = new ClassDAO();
ClassesModel classes = classesDAO.FetchOne(id);
return View("ClassesForm", classes);
}
public ActionResult Delete(int id)
{
ClassDAO classesDAO = new ClassDAO();
classesDAO.Delete(id);
List<ClassesModel> classes = classesDAO.FetchAll();
return View("Index", classes);
}
public ActionResult SearchForm()
{
return View("SearchForm");
}
[HttpPost]
public ActionResult searchForName(string searchPhrase)
{
ClassDAO classesDAO = new ClassDAO();
List<ClassesModel> searchResults = classesDAO.SearchForName(searchPhrase);
return View("Index", searchResults);
}
}
}
and this is where the calendar is created index.cshtml: (home view)
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="calender"></div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span id="eventTitle"></span></h4>
</div>
<div class="modal-body">
<button id="btnDelete" class="btn btn-default btn-sm pull-right">
<span class="glyphicon glyphicon-remove"></span> Remove
</button>
<button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
<span class="glyphicon glyphicon-pencil"></span> Edit
</button>
<p id="pDetails"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="myModalSave" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Save Event</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<input type="hidden" id="hdEventID" value="0" />
<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="chkIsFullDay" checked="checked" /> Is Full Day event</label>
</div>
</div>
<div class="form-group" id="divEndDate" style="display:none">
<label>End</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Theme Color</label>
<select id="ddThemeColor" class="form-control">
<option value="">Default</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="green">Green</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.css" rel="stylesheet" media="print" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
#section Scripts{
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
type: "GET",
url: "/home/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
eventID: v.EventID,
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.End != null ? moment(v.End) : null,
color: v.ThemeColor,
allDay: v.IsFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
}
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
selectedEvent = calEvent;
$('#myModal #eventTitle').text(calEvent.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start:</b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description:</b>' + calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
},
selectable: true,
select: function (start, end) {
selectedEvent = {
eventID: 0,
title: '',
description: '',
start: start,
end: end,
allDay: false,
color: ''
};
openAddEditForm();
$('#calendar').fullCalendar('unselect');
},
editable: true,
eventDrop: function (event) {
var data = {
EventID: event.eventID,
Subject: event.title,
Start: event.start.format('DD/MM/YYYY HH:mm A'),
End: event.end != null ? event.end.format('DD/MM/YYYY HH:mm A') : null,
Description: event.description,
ThemeColor: event.color,
IsFullDay: event.allDay
};
SaveEvent(data);
}
})
}
$('#btnEdit').click(function () {
//Open modal dialog for edit event
openAddEditForm();
})
$('#btnDelete').click(function () {
if (selectedEvent != null && confirm('Are you sure?')) {
$.ajax({
type: "POST",
url: '/home/DeleteEvent',
data: { 'eventID': selectedEvent.eventID },
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModal').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
$('#dtp1,#dtp2').datetimepicker({
format: 'DD/MM/YYYY HH:mm A'
});
$('#chkIsFullDay').change(function () {
if ($(this).is(':checked')) {
$('#divEndDate').hide();
}
else {
$('#divEndDate').show();
}
});
function openAddEditForm() {
if (selectedEvent != null) {
$('#hdEventID').val(selectedEvent.eventID);
$('#txtSubject').val(selectedEvent.title);
$('#txtStart').val(selectedEvent.start.format('DD/MM/YYYY HH:mm A'));
$('#chkIsFullDay').prop("checked", selectedEvent.allDay || false);
$('#chkIsFullDay').change();
$('#txtEnd').val(selectedEvent.end != null ? selectedEvent.end.format('DD/MM/YYYY HH:mm A') : '');
$('#txtDescription').val(selectedEvent.description);
$('#ddThemeColor').val(selectedEvent.color);
}
$('#myModal').modal('hide');
$('#myModalSave').modal();
}
$('#btnSave').click(function () {
//Validation/
if ($('#txtSubject').val().trim() == "") {
alert('Subject required');
return;
}
if ($('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if ($('#chkIsFullDay').is(':checked') == false && $('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var startDate = moment($('#txtStart').val(), "DD/MM/YYYY HH:mm A").toDate();
var endDate = moment($('#txtEnd').val(), "DD/MM/YYYY HH:mm A").toDate();
if (startDate > endDate) {
alert('Invalid end date');
return;
}
}
var data = {
Id: $('#hdEventID').val(),
Subject: $('#txtSubject').val().trim(),
Start: $('#txtStart').val().trim(),
End: $('#chkIsFullDay').is(':checked') ? null : $('#txtEnd').val().trim(),
Description: $('#txtDescription').val(),
ThemeColor: $('#ddThemeColor').val(),
IsFullDay: $('#chkIsFullDay').is(':checked')
}
SaveEvent(data);
// call function for submit data to the server
})
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
</script>
}
and the controller
using ClasSaver.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ClasSaver.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetEvents()
{
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
var events = dc.Events.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
[HttpPost]
public JsonResult DeleteEvent(int eventID)
{
var status = false;
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
var v = dc.Events.Where(a => a.EventID == eventID).FirstOrDefault();
if (v != null)
{
dc.Events.Remove(v);
dc.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status = status } };
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
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 am trying to save data and edit that data using the button with Id btnSaveAnContinue. Now, whenever I click on Save And Continue button to save data, the command parameter in post method i.e gets Saveandcontinue which is defined in the button as per required.
But whenever, I try to edit the data and save it by clicking on same button, the command parameter in AddEdit POST method does not get Saveandcontinue, it is null.
The View:
<form asp-controller="Doctor" asp-action="AddEdit" method="post" class="form-horizontal" id="DoctorAddEdit" role="form">
#Html.HiddenFor(c => c.DoctorId)
<div class="m-b-md heading-tp-cls">
<h3 class="m-b-none pull-left">Doctor Information <small id="currentUsersInCase"></small></h3>
<div class="doc-buttons pull-right relative">
<button type="submit" class="btn btn-s-md btn-success saveButton" id="btnSave"><i class="fa fa-save fa-fw"></i>Save And Close</button>
<button type="submit" name="command" value="Saveandcontinue" id="btnSaveAnContinue" class="btn btn-s-md btn-success saveButton "><i class="fa fa-save fa-fw"></i>Save And Continue</button>
</div>
<div class="clearfix"></div>
</div>
<section class="panel panel-default tp-section-cls no-left-right-borders" style="padding-top: 10px;">
<div class="row m-l-none m-r-none bg-light lter">
<section>
<div class="col-lg-2 col-md-2 col-sm-6 error-holder-form hideSubject" id="claimanatFirstNameDiv">
<label>First Name<span class="requAstrik">*</span></label>
<input asp-for="FirstName" id="DFirstName" class="form-control subjectHide" placeholder="" type="text">
<span asp-validation-for="FirstName" class="text-danger error"></span>
</div>
<div class="col-lg-2 col-md-2 col-sm-6 hideSubject" id="claimanatMiddleInitialDiv">
<label>Middle Name</label>
<input asp-for="MiddleInitial" id="DMidName" class="form-control subjectHide" placeholder="" type="text">
</div>
</section>
</div>
</section>
</form>
GET method for AddEdit:
public IActionResult AddEdit(int id = 0, bool flag = false)
{
var getDoctorById = _doctorService.GetDoctorInfoById(id);
return View(getDoctorById);
}
POST method for AddEdit:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddEdit(DoctorInfoModel doctorInfo, string command)
{
bool isAjaxCall = HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
if (isAjaxCall)
{
return Content("Saved");
}
if (ModelState.IsValid)
{
var result = 0;
int userId = User.GetUserId();
doctorInfo.CreatedBy = userId;
var saveAndGetUserId = 0;
if (doctorInfo.DoctorId == 0)
{
saveAndGetUserId = _doctorService.SaveUserInfo(doctorInfo);
var user = new ApplicationUser { UserName = doctorInfo.UserName, Email = doctorInfo.DocEmail, UserId = saveAndGetUserId };
var getResult = await _userManager.CreateAsync(user, doctorInfo.Password);
_doctorService.SaveUserRole(user.Id);
}
else
{
var getUserId = _doctorService.GetUser(doctorInfo);
var user = _userManager.Users.FirstOrDefault(c => c.UserId == getUserId);
user.UserName = doctorInfo.UserName;
user.Email = doctorInfo.DocEmail;
if (doctorInfo.Password != null && !"Password#123".Equals(doctorInfo.Password))
{
user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, doctorInfo.Password);
}
try
{
var result1 = await _userManager.UpdateAsync(user);
}
catch (Exception ex)
{
throw;
}
}
var getSaveResult = _doctorService.SaveDoctor(doctorInfo, saveAndGetUserId);
if (getSaveResult.Id > 0)
{
Success(getSaveResult.MessageBody);
}
else
{
Warning(getSaveResult.MessageBody);
}
if (command == "Saveandcontinue")
{
return RedirectToAction(nameof(DoctorController.AddEdit), new { id = getSaveResult.Id, flag = true });
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Doctor");
}
}
Warning("Failed to save Doctor, try again later.");
return View("AddEdit", doctorInfo);
}
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
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);
}