I'm trying to set values to table containing textboxes in each cell. For instance a table having a first column containing names, and rest of the columns containing textboxes to add marks of the given assignment for individual students. For that I used dictionary to hold given marks by the instructor and when the page is load, the marks are set to the relevant textboxes. however my iteration over Dictionary in jquery doesn't seem to be really working. I'm missing somewhere in loop. Below is my code.
public class StudentAssignments
{
public string Id { get; set; }
public Models.Assignment assignment { get; set; }
public Models.User user { get; set; }
public DateTime? SubmissionDate { get; set; }
public string Result { get; set; }
public Models.File assignmentfiles {get;set;}
}
public class Assignment
{
public string Id { get; set; }
public string batchid { get; set; }
public List<SelectListItem> batchnumber { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime? DueDate { get; set; }
public Models.File file { get; set; }
}
public class File
{
public string strId { get; set; }
public string strName { get; set; }
public string strPath { get; set; }
public string strSize { get; set; }
}
InstructorController.cs
[HttpPost]
public ActionResult AssignedStudents(string id)
{
//Get Student Assignments
Models.StudentAssignments studentAssignment = new Models.StudentAssignments();
Context.Assignment contAssignment = new Context.Assignment();
CreateUser contUser = new CreateUser();
Dictionary<string, Dictionary<string, List<Models.StudentAssignments>>> dict =
new Dictionary<string, Dictionary<string, List<Models.StudentAssignments>>>();
var studentslist = contStudent.getAllStudentBatchList().Where(p => p.batchId == id).Select(p => p.studentId).ToList();
var assignmentid = contAssignment.lstAssignment().Where(p => p.batchid == id).Select(p=>p.Id).ToList();
foreach(var items in studentslist)
{
dict.Add(items.ToString(), new Dictionary<string, List<Models.StudentAssignments>>());
foreach (var item1 in assignmentid)
{
dict[items].Add(item1.ToString(), GetStudentFiles(items, item1));
}
}
ViewBag.StudentAssignment = dict;
}
private List<Models.StudentAssignments> GetStudentFiles(string stdid, string assgnid)
{
Context.Assignment contAssignment = new Context.Assignment();
CreateUser contuser = new CreateUser();
List<Models.StudentAssignments> lstassgn = new List<Models.StudentAssignments>();
var details = (from t1 in contAssignment.GetStudentAssignments()
join
t2 in contAssignment.GetStudentAssignmentsFiles() on
t1.Id equals t2.assignment.Id
join t3 in contuser.GetAllUsers() on t1.user.Id equals t3.Id
where t1.assignment.Id == assgnid && t1.user.Id == stdid
select new { t1,t2,t3 }).ToList();
foreach (var item in details)
{
Models.StudentAssignments assignment = new Models.StudentAssignments();
assignment.assignment = new Models.Assignment();
assignment.Id = item.t1.Id;
assignment.Result = item.t1.Result;
assignment.assignmentfiles = new Models.File();
assignment.assignmentfiles.strId = item.t2.Id;
assignment.assignmentfiles.strPath = item.t2.assignmentfiles.strPath;
assignment.user = new Models.User();
assignment.user.Id = item.t3.Id;
assignment.user.FirstName = item.t3.FirstName;
assignment.user.LastName = item.t3.LastName;
lstassgn.Add(assignment);
}
return lstassgn;
}
AssignedStudents.cshtml
<div class="col-md-12">
<h2>Submitted Assignments</h2>
<table class="table table-bordered table-responsive table-hover" id="tbl">
<tr>
<th>
Name
</th>
<th>
Assignment 1
</th>
</tr>
#foreach (var item in ViewBag.StudentAssignment)
{
bool flag = true;
<tr class="item">
#foreach (var item1 in item.Value)
{
foreach (var item2 in item1.Value)
{
if (flag == true)
{
<td>
#item2.user.FirstName
</td>
flag = false;
}
break;
}
<td>
#foreach (var item2 in item1.Value)
{
<img src="#" />
}
#foreach (var item2 in item1.Value)
{
if (item2.Result != null && item2.Result != "Pending")
{
<div><input type="text" value="#item2.Result" class="txtbox" id=#Guid.NewGuid().ToString() disabled="disabled"/></div>
}
else
{
<div><input type="text" class="txtbox" id=#Guid.NewGuid().ToString() /></div>
}
<input type="hidden" id="stdassgnid" value="#item2.Id" />
break;
}
</td>
}
</tr>
}
</table>
<input type="button" id="saveResult" value="Save Result" class="btn btn-success" />
</div>
Edited:-
Since I've managed to pass the results in the required textboxes. I'm here surrounded by another issue which is the next assignment submission. The first column contains the submitted marks already, and this time instructor would carry out the marking of the next assignment. Therefore, The system would look for the next column as the previous column already contains marks.
$("#saveResult").click(function () {
$("#tbl tr.item").each(function () {
$(this).find("input.txtbox").attr("disabled", "disabled");
var Mkrs = $(this).find("input.txtbox").val();
var Id = $(this).find("#stdassgnid").val();
alert(Mkrs)
$.ajax({
type: "POST",
url: '#Url.Action("UpdateResult", "Assignment")',
data: { Marks: Mkrs, studentAssgnId: Id},
dataType: "json",
success: function (data) {
if(data.message!=null)
{
alert(data.message)
}
}
})
});
Related
I am still currently debugging the system becauae it seems to load all the data. My system has 4218 records. I have successfully used the Skip and Take in the system but the problem is that it only loads the first 10 records. How to call the other records? I want to do the Server Side Pagination.
This is the entity class:
public List<NonconformingServiceModel> GetAllNSIssue(int UserID, int pageNumber = 1)
{
using (SIRManagementSystemEntities _entities = new SIRManagementSystemEntities())
{
NonconformingServiceModel NSModel = new NonconformingServiceModel();
var date1 = new DateTime(2000, 1, 1, 1, 0, 0);
List<NonconformingServiceModel> result = new List<NonconformingServiceModel>();
var userData = (from _user in _entities.Administrators where _user.UserID == UserID select _user).FirstOrDefault();
if (userData != null)
{
if (userData.UserType == 1 || userData.UserType == 0 || userData.UserID == 38)
{
result = (from _NSDetails in _entities.NonconformingServices
join _creator in _entities.Administrators on _NSDetails.CreatedBy equals _creator.UserID
join _SIRDetails in _entities.SIR_InitialDetail on _NSDetails.NS_ID equals _SIRDetails.NSCCRefID into _sir
from _SIRDetails in _sir.DefaultIfEmpty()
select new NonconformingServiceModel
{
ID = _NSDetails.NS_ID,
Type = _NSDetails.Type,
Category = _NSDetails.Category,
Reason = _NSDetails.Reason,
Remarks = _NSDetails.Remarks,
ModeThru = _NSDetails.Mode,
DateDelivered = _NSDetails.DateDelivered,
LoadingDate = _NSDetails.LoadingDate,
DateIssue = _NSDetails.DateIssue,
Origin = _NSDetails.Origin,
Destination = _NSDetails.Destination,
CartonNumber = _NSDetails.CartonNumber,
ShipmentNumber = _NSDetails.ShipmentNumber,
ShipperName = _NSDetails.ShipperName,
ConsigneeName = _NSDetails.ConsigneeName,
Address = _NSDetails.Address,
NSGroup = _NSDetails.NSGroup,
NSCode = _NSDetails.NSCode,
OtherType = _NSDetails.OtherType,
CreatedByID = _NSDetails.CreatedBy,
CreatedByName = _creator.FirstName + " " + _creator.LastName,
SIRCode = _SIRDetails.Code == null ? "" : _SIRDetails.Code,
SIRDateIssue = _SIRDetails.IssueDate == null ? date1 : _SIRDetails.IssueDate,
SIRDueDate = _SIRDetails.DueDate == null ? date1 : _SIRDetails.DueDate,
Status = _SIRDetails.Code == null ? 0 : _SIRDetails.Status
}).ToList();
}
else
{
result = (from _creator in _entities.Administrators
join _NSDetails in _entities.NonconformingServices on _creator.UserID equals _NSDetails.CreatedBy
join _mapping in _entities.CCNSDEPTMappings on _NSDetails.NSCode equals _mapping.NSCode
join _SIRDetails in _entities.SIR_InitialDetail on _NSDetails.NS_ID equals _SIRDetails.NSCCRefID into _sir
from _SIRDetails in _sir.DefaultIfEmpty()
where _creator.Department == userData.Department || _mapping.ConcernDeptID == userData.Department || _creator.Department == userData.SecondDept || _mapping.ConcernDeptID == userData.SecondDept
select new NonconformingServiceModel
{
ID = _NSDetails.NS_ID,
Type = _NSDetails.Type,
Category = _NSDetails.Category,
Reason = _NSDetails.Reason,
Remarks = _NSDetails.Remarks,
ModeThru = _NSDetails.Mode,
DateDelivered = _NSDetails.DateDelivered,
LoadingDate = _NSDetails.LoadingDate,
DateIssue = _NSDetails.DateIssue,
Origin = _NSDetails.Origin,
Destination = _NSDetails.Destination,
CartonNumber = _NSDetails.CartonNumber,
ShipmentNumber = _NSDetails.ShipmentNumber,
ShipperName = _NSDetails.ShipperName,
ConsigneeName = _NSDetails.ConsigneeName,
Address = _NSDetails.Address,
NSGroup = _NSDetails.NSGroup,
NSCode = _NSDetails.NSCode,
OtherType = _NSDetails.OtherType,
CreatedByID = _NSDetails.CreatedBy,
CreatedByName = _creator.FirstName + " " + _creator.LastName,
SIRCode = _SIRDetails.Code == null ? "" : _SIRDetails.Code,
SIRDateIssue = _SIRDetails.IssueDate == null ? date1 : _SIRDetails.IssueDate,
SIRDueDate = _SIRDetails.DueDate == null ? date1 : _SIRDetails.DueDate,
Status = _SIRDetails.Code == null ? 0 : _SIRDetails.Status
}).ToList();
// var _result = (List<NonconformingServiceModel>)result.GroupBy(x => x.NSCode).Select(x => x.FirstOrDefault()).ToList().Skip((pageNumber - 1) * 10).Take(10);
}
var _result = result.GroupBy(x => x.NSCode).Select(x => x.FirstOrDefault()).ToList().Skip((pageNumber - 1) * 10).Take(10);
foreach (var item in _result)
{
if (item.Status == null || item.Status == 0)
{
if (item.SIRCode != "")
{
DateTime dueDate = item.SIRDueDate.Value;
DateTime now = DateTime.Now;
if (now.Date > dueDate.Date)
{
item.FormatIssueDate = "late";
}
else
{
item.FormatIssueDate = "not";
}
}
else
{
item.SIRCode = "";
item.SIRDateIssue = null;
item.SIRDueDate = null;
item.Status = 0;
}
}
else
{
item.SIRID = (from _sirDet in _entities.SIR_InitialDetail where _sirDet.Code == item.SIRCode select _sirDet.sirID).FirstOrDefault();
item.SubmissionDate = (from _sirDet in _entities.SIR_InitialDetail where _sirDet.sirID == item.SIRID select _sirDet.SubmissionDate).FirstOrDefault();
item.CEDueDate = (from _sirCA in _entities.SIR_CorrectActDetail where _sirCA.Cor_SIRID == item.SIRID select _sirCA.CEDueDate).FirstOrDefault();
item.FormatIssueDate = "submitted";
}
item.TypeName = (from _type in _entities.DDNSTypes where _type.TypeID == item.Type select _type.Label).FirstOrDefault();
if (item.Type == 19)
{
item.TypeName = item.OtherType;
}
item.CategoryName = (from _cat in _entities.DDCategories where _cat.SIRCAT_ID == item.Category select _cat.Label).FirstOrDefault();
var deptArray = (from _mapping in _entities.CCNSDEPTMappings
join _dept in _entities.Departments on _mapping.ConcernDeptID equals _dept.DeptID
where _mapping.NSCode == item.NSCode
select _dept.DeptID).ToList();
var deptCode = (from _mapping in _entities.CCNSDEPTMappings
join _dept in _entities.Departments on _mapping.ConcernDeptID equals _dept.DeptID
where _mapping.NSCode == item.NSCode
select _dept.DeptCode).ToList();
item.ConcernedDeptArray = deptArray;
item.ConcernedDeptName = deptCode;
item.Company = (from _user in _entities.Administrators
join _dept in _entities.Departments on _user.Department equals _dept.DeptID
where _user.UserID == item.CreatedByID select _dept.Company).FirstOrDefault();
}
return _result.ToList();
}
return null;
}
}
This is the view model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SIMS.Model.Models
{
public class NonconformingServiceModel
{
public int ID { get; set; }
public byte Type { get; set; }
public string TypeName { get; set; }
public string OtherType { get; set; }
public byte Category { get; set; }
public string CategoryName { get; set; }
public string OtherCategory { get; set; }
public string Reason { get; set; }
public string Remarks { get; set; }
public string ModeThru { get; set; }
public DateTime? DateDelivered { get; set; }
public DateTime? LoadingDate { get; set; }
public DateTime DateIssue { get; set; }
public string ConcernedDeptString { get; set; }
public List<int> ConcernedDeptArray { get; set; }
public List<string> ConcernedDeptName { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public string CartonNumber { get; set; }
public string ShipmentNumber { get; set; }
public string ShipperName { get; set; }
public string ConsigneeName { get; set; }
public string Address { get; set; }
public string NSGroup { get; set; }
public int CreatedByID { get; set; }
public string CreatedByName { get; set; }
public int CreatedByDept { get; set; }
public int UserType { get; set; }
public string NSCode { get; set; }
public byte? Status { get; set; }
public int? SIRID { get; set; }
public string SIRCode { get; set; }
public DateTime? SIRDateIssue { get; set; }
public DateTime? SIRDueDate { get; set; }
public DateTime? SubmissionDate { get; set; }
public DateTime? CEDueDate { get; set; }
public DateTime? DetectionDate { get; set; }
public string FormatIssueDate { get; set; }
public int UserID { get; set; }
public int? Company { get; set; }
}
}
This is the controller class:
public ActionResult GetAllNSLogDetails(int UserID)
{
JsonResult _json = new JsonResult();
NonconformingServiceManager _NSManager = new NonconformingServiceManager();
_json.Data = _NSManager.GetAllNSIssue(UserID);
_json.MaxJsonLength = Int32.MaxValue;
return _json;
}
This is the view:
<!-- Begin Page Content -->
<div class="container-fluid">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item active" aria-current="page">Nonconforming Service</li>
</ol>
</nav>
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Nonconforming Services Log</h6>
<div class="text-right">
<button type="button" class="btn btn-outline-info" onclick="window.location.reload();">Show All Data</button>
<button type="button" data-toggle="modal" data-target=".modal-filter-table" class="btn btn-outline-info"><i class="fas fa-filter"></i>Sort by</button>
<button type="button" onclick="CreateNewConcern()" class="btn btn-outline-primary"><i class="far fa-plus-square"></i> Create New NS</button>
</div>
</div>
<div class="card-body">
<div class="card-body table-responsive">
<table id="NonconformingServiceLogGrid" class="table table-hover" style="width:100%">
<thead>
<tr>
<th>Date Created</th>
<th>NS Code</th>
<th>SIR Code</th>
<th>Date Issue</th>
<th>Due Date</th>
<th>Submission Date</th>
<th>Type</th>
<th>Category</th>
<th>Concerned Dept.</th>
<th>SIR Status</th>
<th>CE Due Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Date Created</th>
<th>NS Code</th>
<th>SIR Code</th>
<th>Date Issue</th>
<th>Due Date</th>
<th>Submission Date</th>
<th>Type</th>
<th>Category</th>
<th>Concerned Dept.</th>
<th>SIR Status</th>
<th>CE Due Date</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
All answers will be appreciated.
You required one Pagination Class as per below example:
Response.cs
public class Response<T>
{
public Response()
{
}
public Response(T data)
{
Succeeded = true;
Message = string.Empty;
Errors = null;
Data = data;
}
public T Data { get; set; }
public bool Succeeded { get; set; }
public string[] Errors { get; set; }
public string Message { get; set; }
}
Second class is PageResponse.cs
public class PagedResponse<T> : Response<T>
{
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public int TotalRecords { get; set; }
public int TotalFilteredRecords { get; set; }
public PagedResponse(T data, int pageNumber, int pageSize)
{
PageNumber = pageNumber;
PageSize = pageSize;
Data = data;
Message = null;
Succeeded = true;
Errors = null;
}
}
In controller you just need to fetch the data like below:
[HttpGet]
public async Task<IActionResult> GetAllDetailAsync(int pageNumber)
{
int pageSize=10;
var pagedData = await _Service.GetData(pageNumber, pageSize);
PagedResponse<List<MyModel>> pagedResponse = new(pagedData, pageNumber, pageSize);
pagedResponse.TotalRecords = await _Service.GetTotalRecords();
int totalPages = pagedResponse.TotalRecords / pagedResponse.PageSize;
if ((pagedResponse.TotalRecords % pagedResponse.PageSize) != 0)
{
totalPages++;
}
pagedResponse.TotalPages = totalPages;
return Ok(pagedResponse);
}
I am rather new to MVC so please bear with me.
My goal at hand is to POST a checkboxfor html helper that contains the property called "Verified" to my controller using Ajax. I did mounds of research and yielded this post which is very similar, however it still does not reach the controller and instead I receive a 505 error. checkboxfor Ajax link. This post didn't show how the controller handled the data being passed to the and I am lead to believe that may be my issue but I am not certain. Or it may be something with the foreach block doing some weird stuff.(Side note on the table, we use datatables.net library for table formatting). Below is my code...
Model (comes directly from the EF entity class and is brought in via Meta Data)
namespace Entities
{
public class FPDrinkingWater : AccessibleRecord<FPDrinkingWater>
{
public FPDrinkingWater();
public bool Approved { get; set; }
public string ApprovedBy { get; set; }
public DateTime? ApprovedDate { get; set; }
public string Clorinated { get; set; }
public DateTime? CollectionDate { get; set; }
public TimeSpan? CollectionTime { get; set; }
public string Collectors { get; set; }
public string Comments { get; set; }
public override string CreatedBy { get; set; }
public override DateTime CreatedDate { get; set; }
public bool Deleted { get; set; }
public bool EC { get; set; }
public override int Id { get; set; }
public string Location { get; set; }
public bool RAG { get; set; }
//
// Summary:
// Drinking water record
public override string RecordName { get; }
public short? Replicate { get; set; }
public virtual SampleLog SampleLog { get; set; }
public int SID { get; set; }
public bool SWAT_LAB { get; set; }
public bool TIMS { get; set; }
public override string UpdatedBy { get; set; }
public override DateTime? UpdatedDate { get; set; }
public bool Verified { get; set; }
public string VerifiedBy { get; set; }
public DateTime? VerifiedDate { get; set; }
public override void UpdateTo(FPDrinkingWater entity);
protected override void ParameterChecks();
}
}
Controller action to populate view:
//unverified Drinking Water log
[OpenAction]
public async Task<ActionResult> UnverifiedDrinkingWaterLog(AlertModel alert)
{
//return partial Drinking water log view
return await UnverifiedDataTableAsync<FPDrinkingWater>(alert);
}
Definition of UnverifiedDataTableAsync:
//Unverified data table
[OpenAction]
public async Task<ActionResult> UnverifiedDataTableAsync<TEntity>(AlertModel alert, string viewName = null) where TEntity : class
{
// get data
var data = (from a in await LimsManager.AllAsync<TEntity>()
select a).ToList();
//LimsManager.AllAsync returns the entire context contents of the Entity in a List then the view tests if `Verified` is not populated.
// create sample log model with alert
var response = new TableModel<TEntity>
{
Alert = alert,
Data = data
};
// return partial data view
return PartialView(viewName ?? $"_Unverified{typeof(TEntity).Name}Table", response);
}
Controller update action:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyDrinkingWater(FPDrinkingWater drinkingWater, string id )
{
//create alert model
var response = new AlertModel();
//check model state
if(ModelState.IsValid)
{
//add the verifier to the DrinkingWater record
drinkingWater.Verified = true;
drinkingWater.VerifiedBy = User.Identity.Name;
drinkingWater.VerifiedDate = DateTime.Now;
//update the drinking water with the new verified information
var result = await LimsManager.UpdateAsync(drinkingWater);
//check update result
if(result.Succeeded)
{
response.AddInfo($"All SID's successfully verified in the database.", BSContextualTypes.success);
}
else
{
//add failure to alert
response.AddInfo($"Unable to verify SID's in database.", BSContextualTypes.warning);
}
}
else
{
InvalidState(response);
}
return await UnverifiedDrinkingWaterLog(response);
}
The view should iterate over the context of the entity and building the table for each record it finds that is not verified:
#model MyProgram.Application.TableModel<Entities.FPDrinkingWater>
#{
Layout = null;
var insertionMode = InsertionMode.Replace;
var fail = "displayFailure";
var target = "UnverifiedDrinkingWaterContent";
var ajax = "UnverifiedDrinkingWaterLogLoader";
var verify = Html.UserHasClaim("FP/DrinkingWater/VerifyDrinkingWater");
}
<br />
#if (Model != null && Model.Alert != null && Model.Alert.Message != null)
{
#Html.Alert(Model.Alert)
}
#MyHelper.Loader(ajax)
<table id="UnverifiedDrinkingWaterTable" class="table table-hover">
<thead>
<tr>
<th>#Html.LabelFor(m => m.Data.FirstOrDefault().SID)</th>
<th>#Html.LabelFor(m => m.Data.FirstOrDefault().Location)</th>
<th>#Html.LabelFor(m => m.Data.FirstOrDefault().Replicate)</th>
<th>#Html.LabelFor(m => m.Data.FirstOrDefault().CollectionDate)</th>
<th>#Html.LabelFor(m => m.Data.FirstOrDefault().CollectionTime)</th>
<th>#Html.LabelFor(m => m.Data.FirstOrDefault().Collectors)</th>
<th>#Html.LabelFor(m => m.Data.FirstOrDefault().Clorinated)</th>
<th>#Html.LabelFor(m => m.Data.FirstOrDefault().Comments)</th>
<th>#Html.LabelFor(m => m.Data.FirstOrDefault().Verified)</th>
</tr>
</thead>
<tbody>
#if (Model.Data.Any(v => !v.Verified))
{
foreach (var log in Model.Data.Where(v => !v.Verified))
{
<tr data-record-id="#log.Id">
<td>#log.SID</td>
<td>#log.Location</td>
<td>#log.Replicate</td>
<td>#log.CollectionDate.Value.ToShortDateString()</td>
<td>#log.CollectionTime</td>
<td>#log.Collectors</td>
<td>#log.Clorinated</td>
<td>#log.Comments</td>
<td>#Html.CheckBoxFor(m => log.Verified, new { data_url = Url.Action("VerifyDrinkingWater", "DrinkingWater"), id = "mycheckbox", #class = "toggle" })</td>
</tr>
}
}
else
{
<tr>
<td colspan="#Html.ColumnCount(3)"><em>No Drinking Water data to verify.</em></td>
</tr>
}
</tbody>
</table>
<hr />
#if (Model.Data.Count > 0)
{
<script>
$(document).ready(function () {
makeDataTable('UnverifiedDrinkingWaterTable');
$(function () {
$('.toggle').change(function () {
var self = $(this);
var url = self.data('url');
var id = self.attr('id');
var value = self.prop(':checked');
$.ajax({
url: url,
data: { id: id },
type: 'POST',
success: function (result) {
alert(response)
}
});
});
});
});
</script>
}
Generated HTML:
<tr data-record-id="3" role="row" class="odd">
<td>5</td>
<td>Location</td>
<td>1</td>
<td>3/31/1997</td>
<td>18:00:00</td>
<td>YY</td>
<td>Y</td>
<td></td>
<td><input class="toggle" data-url="/FP/DrinkingWater/VerifyDrinkingWater" data-val="true" data-val-required="The Verified field is required." id="mycheckbox" name="log.Verified" type="checkbox" value="true"><input name="log.Verified" type="hidden" value="false"></td>
</tr>
And that data-record-id matches the ones in the database.
I am trying to populate an HTML table with data from a table in my database. The issue is simply that the HTML table is not getting populated with any data.
Here is the ViewModel:
public class TestViewModel
{
public string MatchedId { get; set; }
public string UnmatchedId { get; set; }
public string Auth { get; set; }
public DateTime CreditDate { get; set; }
public string CreditNumber { get; set; }
public decimal CreditAmount { get; set; }
public DateTime DeniedDate { get; set; }
public int DeniedReasonId { get; set; }
public string DeniedNotes { get; set; }
}
Controller Action:
[HttpPost]
public ActionResult UploadValidationTable(HttpPostedFileBase csvFile)
{
var inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
var cc = new CsvContext();
var filePath = uploadFile(csvFile.InputStream);
var model = cc.Read<Credit>(filePath, inputFileDescription);
try
{
var entity = new Entities();
//model here is the .csv, doesn't have anything to do with this issue
foreach (var item in model)
{
var tc = new TemporaryCsvUpload
{
Id = item.Id,
CreditAmount = item.CreditAmount,
CreditDate = item.CreditDate,
CreditNumber = item.CreditNumber,
DeniedDate = item.DeniedDate,
DeniedReasonId = item.DeniedReasonId,
DeniedNotes = item.DeniedNotes
};
entity.TemporaryCsvUploads.Add(tc);
}
entity.SaveChanges();
System.IO.File.Delete(filePath);
//This is where the database table is getting filled
entity.Database.ExecuteSqlCommand("Insert into CsvReport Select p.Id as MatchedId, case when p.Id is null then t.Id end as UnmatchedId, p.Auth,p.CreditDate, p.CreditNumber,p.CreditAmount, p.DeniedDate,p.DeniedReasonId, p.DeniedNotes from TemporaryCsvUpload t left join PermanentTable p on p.Id = t.Id;");
TempData["Success"] = "Updated Successfully";
}
catch (LINQtoCSVException)
{
TempData["Error"] = "Upload Error: Ensure you have the correct header fields and that the file is of .csv format.";
}
return View("Upload");
}
View:
#model IEnumerable<TestProject.TestViewModel>
#if (Model != null)
{
foreach (var item in Model.Where(x => x.IdMatched != null))
{
<tr>
<td>
#item.MatchedId
</td>
<td>
#item.Auth
</td>
<td>
#item.CreditDate
</td>
<td>
#item.CreditNumber
</td>
<td>
#item.CreditAmount
</td>
<td>
#item.DeniedDate
</td>
<td>
#item.DeniedReasonId
</td>
<td>
#item.DeniedNotes
</td>
</tr>
}
}
It's a little weird because I am populating the database with an SQL command. What am I missing here? Do I need to try and pass it through the controller action? Let me know if you need more information. Thanks!
Edit
I tried to pass the instance through, but I may still be doing it incorrectly:
var testModel = new TestViewModel();
return View("Upload", testModel);
Here is what its padding through:
public class TestViewModel
{
public IEnumerable<Test> Test { get; set; }
}
Made an answer so essentially the view doesn't know what to render you need to pass an actual filled model (in your case an IEnumerable to the view). This can be done using the method:
View("Upload", viewModelList);
Controller.View docs on MSDN
It looks like you are not adding any data to your view model.
If your view model is a collection of Test objects, you need to add some
Test objects to the collection.
var model = new TestViewModel()
{
Test = new List<Test>() { new Test(), new Test(), ... }
}
return View("Upload", model);
I'm trying to pass few ViewModels to the same View via ViewData. Unfortunately I'm new to MVC and I do not have idea what's wrong with that.
Here is first DataViewModel:
public class TagsViewModel
{
public string TagName { get; set; }
public int TagId { get; set; }
}
And another one:
public class ShortPostViewModel
{
public int PostId { get; set; }
public string PostSubject { get; set; }
public DateTime? PostCreated { get; set; }
public string PostImage { get; set; }
public string PostAuthor { get; set; }
public byte? PostRating { get; set; }
public List<PostTagsViewModel> PostedTags { get; set; }
}
Here is repository:
public IEnumerable<BlogPostViewModel.ShortPostViewModel> GetLast20()
{
var last = from a in _db.blog_post
orderby a.Posted descending
select new BlogPostViewModel.ShortPostViewModel
{
PostId = a.ID,
PostAuthor = (from u in _db.users where u.ID == a.Author
select u.Login).FirstOrDefault(),
PostCreated = a.Posted,
PostImage = a.PostAvatar,
PostRating = a.Rating,
PostSubject = a.Subject,
PostedTags = (from b in _db.tags
join c in _db.posted_tags on b.ID equals c.TagID
where c.PostID == a.ID
select new PostTagsViewModel
{
TagId = b.ID,
TagName = b.TagName
}).ToList()
};
return last.Take(20);
}
And one more:
public IEnumerable<TagsViewModel> GetAll()
{
var t = from a in _db.tags
select new TagsViewModel
{
TagId = a.ID,
TagName = a.TagName
};
return t;
}
So here is Controller:
public ActionResult Index()
{
ViewData["ShortPost"] = _postRepository.GetLast20().AsEnumerable();
ViewData["Tags"] = _tagsRepository.GetAll().AsEnumerable();
return View();
}
So on the View:
<ul class="list-group">
#foreach (var item in (IEnumerable<ShortPostViewModel>)ViewData["ShortPost"])
{
<li class="list-group-item">
<img src="#item.PostImage" alt=""/>
<h3>#Html.ActionLink(#item.PostSubject, "Details", "BlogPost", new { id = item.PostId }, null)</h3>
Создано: #item.PostCreated. Автор: #item.PostAuthor. Оценка: #item.PostRating.
<p>
Темы статьи:
#foreach (var tag in #item.PostedTags)
{
<i class="glyphicon glyphicon-tag"></i> #Html.ActionLink(#tag.TagName, "Tag", "Search", new { id = tag.TagId }, null)
}
</p>
</li>
}
</ul>
</div>
<div class="col-md-4">
#foreach (var tag in (IEnumerable<TagsViewModel>)ViewData["Tags"])
{
<span class="label label-info"><i class="glyphicon glyphicon-tag"></i> #Html.ActionLink(#tag.TagName, "Tag", "Search", new { id = tag.TagId }, null)</span>
}
</div>
This all look just fine for me. Could you advise how should I fix that?
Instead of using several ViewData, I would recommend using a new ViewModel class that have a List<TagsViewModel> property and a List<ShortPostViewModel> property so you don't have to do the conversions in the view. Let's say the ViewModel is named CustomViewModel
public class CustomViewModel
{
public CustomViewModel()
{
this.ShortPosts = new List<ShortPostViewModel>();
this.Tags = new List<TagsViewModel>();
}
public List<ShortPostViewModel> ShortPosts { get; set; }
public List<TagsViewModel> Tags { get; set; }
}
then in your controller
public ActionResult Index()
{
CustomViewModel model = new CustomViewModel();
model.ShortPosts = _postRepository.GetLast20().ToList();
model.Tags = _tagsRepository.GetAll().ToList();
return View(model);
}
Make sure you have this at the top of your view code
#model CustomViewModel
You can enumerate the items of ShortPosts in your view as below
#foreach (var item in Model.ShortPosts)
and enumerate the items of Tags as below
#foreach (var tag in Model.Tags)
I have the following form:
#model Teesa.Models.SearchModel
#using (Html.BeginForm("Index", "Search", FormMethod.Get, new { id = "SearchForm" }))
{
<div class="top-menu-search-buttons-div">
#if (!MvcHtmlString.IsNullOrEmpty(Html.ValidationMessageFor(m => m.SearchText)))
{
<style type="text/css">
.top-menu-search-text
{
border: solid 1px red;
}
</style>
}
#Html.TextBoxFor(q => q.SearchText, new { #class = "top-menu-search-text", id = "SearchText", name = "SearchText" })
#Html.HiddenFor(q=>q.Page)
<input type="submit" value="search" class="top-menu-search-submit-button" />
</div>
<div id="top-menu-search-info" class="top-menu-search-info-div">
Please Select one :
<hr style="background-color: #ccc; height: 1px;" />
<div class="top-menu-search-info-checkbox-div">
#Html.CheckBoxFor(q => q.SearchInBooks, new { id = "SearchInBooks", name = "SearchInBooks" })
<label for="SearchInBooks">Books</label>
</div>
<div class="top-menu-search-info-checkbox-div">
#Html.CheckBoxFor(q => q.SearchInAuthors, new { id = "SearchInAuthors" })
<label for="SearchInAuthors">Authors</label>
</div>
<div class="top-menu-search-info-checkbox-div">
#Html.CheckBoxFor(q => q.SearchInTags, new { id = "SearchInTags" })
<label for="SearchInTags">Tags</label>
</div>
}
and the following Controller and Models :
namespace Teesa.Models
{
public class SearchModel
{
[Required(ErrorMessage = "*")]
public string SearchText { get; set; }
public bool SearchInTags { get; set; }
public bool SearchInAuthors { get; set; }
public bool SearchInBooks { get; set; }
public int Page { get; set; }
public List<SearchBookModel> Result { get; set; }
public List<SimilarBookModel> LatestBooks { get; set; }
}
public class SearchBookModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Summary { get; set; }
public List<Tags> Tags { get; set; }
public string StatusName { get; set; }
public string SubjectName { get; set; }
public string ThumbnailImagePath { get; set; }
public string BookRate { get; set; }
public string RegistrationDate { get; set; }
public int NumberOfVisit { get; set; }
}
}
[HttpGet]
public ActionResult Index(SearchModel model)
{
FillSearchModel(model);
if (ModelState.IsValid)
{
string page = model.Page;
DatabaseInteract databaseInteract = new DatabaseInteract();
model.Result = new List<SearchBookModel>();
List<Book> allBooks = databaseInteract.GetAllBooks();
List<Book> result = new List<Book>();
#region
if (model.SearchInTags)
{
var temp = (from item in allBooks
from tagItem in item.Tags
where tagItem.Name.Contains(model.SearchText)
select item).ToList();
result.AddRange(temp);
}
if (model.SearchInBooks)
{
var temp = (from item in allBooks
where item.عنوان.Contains(model.SearchText)
select item).ToList();
result.AddRange(temp);
}
if (model.SearchInAuthors)
{
var temp = (from item in allBooks
where item.Author.Contains(model.SearchText)
select item).ToList();
result.AddRange(temp);
}
#endregion
#region Paging
string itemsPerPage = databaseInteract.GetItemsPerPage();
int ItemInPage = int.Parse(itemsPerPage);
var pagingParams = Helpers.SetPagerParameters(page, ItemInPage, result);
ViewBag.AllPagesCount = pagingParams.AllPagesCount;
ViewBag.CurrentPageNumber = pagingParams.CurrentPageNumber;
ViewBag.CountOfAllItems = pagingParams.CountOfAllItems.ToMoneyFormat().ToPersianNumber();
result = pagingParams.ListData as List<Book> ?? result;
#endregion
foreach (var item in result)
{
var bookRate = (item.BookRate == null || item.BookRate.Count == 0)
? 0.0
: item.BookRate.Average(q => q.Rate);
model.Result.Add(new SearchBookModel
{
Author = item.Author,
Id = item.Id,
.
.
.
});
}
}
else
{
model.Result = new List<SearchBookModel>();
}
return View(model);
}
When I submit the form I see the following query strings(Notice the duplicate names) :
http://localhost:2817/Search?SearchText=book&Page=2&SearchInBooks=true&SearchInBooks=false&SearchInAuthors=true&SearchInAuthors=false&SearchInTags=true&SearchInTags=false
But it has to be something like this :
http://localhost:2817/Search?SearchText=book&Page=2&SearchInBooks=true&SearchInAuthors=true&SearchInTags=true
How can I fix it ?
Thanks
Html.Checkbox (and the related For... methods) generate a hidden input for false, and the checkbox for true. This is to ensure that model binding works consistently when binding.
If you must get rid of "false" items resulting from the hidden inputs, you'll need to construct the checkbox inputs yourself (using HTML and not the helper).
<input type="checkbox" id="SearchInBooks" name="SearchInBooks">
Why dont your create a Post Method with a matching name to the Get method. This will ensure that the code is much easier to debug. As you will not have a huge function to go through trying to find problems like this.
I cannot find a where your getting the duplicate url query strings from though.
This will also allow you to bind your results back to the model.
If you want the model binding to happen successfully then you have to go with this way because that is the nature of the Html.CheckBox/Html.CheckBoxFor methods they will render a hidden field as well.
I would suggest rather go with POST to make your life easy. If you still want to use GET then you have to use checkbox elements directly but you have to take care of the model binding issues. Not all the browsers returns "true" when the checkbox is checked for ex. firefox passes "on" so the default model binder throws an error.
Other alternate options is you can go for custom model binder or you can submit the form using jquery by listening to the submit event.