I currently have table that displays a list of all of the issues. I added PagedList.MVC to the application as well as a jquery filterTable the issue is that when I click on a different page using the PagedListPager it loses all of the sort options at the top of the page. I believe I just need to add the parameters to the pagedlistpager but I am not sure how to get the value of the textbox. I was thinking about trying to use jquery and using the val() of the element but not sure if that is the best/easiest way to do this.
Here is my View:
#model PagedList.IPagedList<ApIssues.Models.AP_Tasks>
#using System.Data.SqlClient
#using PagedList.Mvc;
#{
ViewBag.Title = "Index";
}
<div class="search-sort-section">
<h2>Search and Sort</h2>
#using (Html.BeginForm("Index","ApIssues"))
{
<p>
#Html.Label("Company: ")
#Html.DropDownList("company", (SelectList)ViewBag.CompanyList, " ")
#Html.Label("Warehouse: ")
#Html.DropDownList("warehouse", (SelectList)ViewBag.WarehouseList, " ")
#Html.Label("Past Due Only: ")
#Html.DropDownList("pastDue", (SelectList)ViewBag.PastDueList, " ")
#Html.Label("Assigned To/By: ")
#Html.DropDownList("assignedToBy", (SelectList)ViewBag.UsersList, " ")
</p>
<p>
#Html.Label("Open / Completed: ")
#Html.DropDownList("openco", (SelectList)ViewBag.OpenCompList, " ")
#Html.Label("Sort By: ")
#Html.DropDownList("sortBy", (SelectList)ViewBag.SortByList, " ")
#Html.Label("PO #: ")
#Html.TextBox("poNumber")
#Html.Label("Freight #: ")
#Html.TextBox("freightNumber")
#Html.Label("Vendor Name: ")
#Html.TextBox("vendorName")
</p>
<p>
#Html.Label("Issue Date")
#Html.TextBox("beginIssueDate") - #Html.TextBox("endIssueDate")
#Html.Label("Invoice Date")
#Html.TextBox("beginInvoiceDate") - #Html.TextBox("endInvoiceDate")
#Html.Label("Completed Date")
#Html.TextBox("beginCompletedDate") - #Html.TextBox("endCompletedDate")
#Html.Label("Quick Filter: ")
#Html.TextBox("quickFilter")
</p>
<p>
<input type="submit" value="Go" />
<input type="button" value="Printable View" onclick=" location.href = '#Url.Action("PrintablePdf", "ApIssues")' " />
<input type="button" value="Add New Task" onclick=" location.href = '#Url.Action("Create", "ApIssues")' " />
<input type="button" value="Reporting" />
</p>
}
</div>
<div class="issue-table">
<h2>A/P Issues</h2>
<table id="data-table">
<tr>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Task ID", "Index",
new { sortOrder = "TaskID", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Task Date", "Index",
new { sortOrder = "TaskDate", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Invoice Date", "Index",
new { sortOrder = "InvDate", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Assigned To", "Index",
new { sortOrder = "AssignedTo", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("CC", "Index",
new { sortOrder = "CC", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("WHSE", "Index",
new { sortOrder = "Whse", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("PO #", "Index",
new { sortOrder = "PO", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Freight #", "Index",
new { sortOrder = "FreightNo", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Vendor Name", "Index",
new { sortOrder = "VendName", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Req. Completion Date", "Index",
new { sortOrder = "ReqCompDate", CurrentSort = ViewBag.CurrentSort })
</th>
<th style="border: 2px solid black; text-align: center; width: 12%">
#Html.ActionLink("Task Type", "Index",
new { sortOrder = "TaskType", CurrentSort = ViewBag.CurrentSort })
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink(item.TaskID.ToString(), "Task", new { id = item.TaskID })
</td>
<td>
#Html.DisplayFor(modelItem => item.TaskDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.InvDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.AssignedTo)
</td>
<td>
#Html.DisplayFor(modelItem => item.CC)
</td>
<td>
#Html.DisplayFor(modelItem => item.Whse)
</td>
<td>
#Html.DisplayFor(modelItem => item.PO)
</td>
<td>
#Html.DisplayFor(modelItem => item.FreightNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.VendName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReqCompDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.TaskType)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.TaskID })
</td>
</tr>
}
</table>
<br />
<div id='Paging' style="text-align:center">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new {page}))
</div>
</div>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://sunnywalker.github.io/jQuery.FilterTable/jquery.filtertable.min.js"></script>
<script src="~/Scripts/Additional JS/jquery.tablesorter.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('table').filterTable(
{
minRows: 1,
label: "Search :",
inputSelector: "#quickFilter" ,
placeholder: "Keyword"
});
});
</script>
</head>
Here is my action:
public ActionResult Index(string sortOrder,string currentSort, int? page, string company, string warehouse,
string pastDue, string assignedToBy, string openco, string sortBy, string poNumber, string freightNumber,
string vendorName, string beginIssueDate, string endIssueDate, string beginInvoiceDate, string endInvoiceDate,
string beginCompletedDate, string endCompletedDate)
{
//Variable Definitions
const int pageSize = 20;
var pageIndex = 1;
pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
IPagedList<AP_Tasks> tasks = null;
// Instantiate the Entities
var nxtDb = new nxtSQLEntities();
var db = new Accounting_AaronTestEntities();
var usersDb = new PDDAEntities1();
//Query that gets the warehouses, companys, and users from the nxtDB and the PPP DB
var whses = from w in nxtDb.icsds select w.whse;
var coNames = from c in nxtDb.icsds select c.name;
var userDb = new PDDAEntities1();
var query1 = from u in userDb.Users where u.Cono == 1 select new { u.UserName, u.FirstName, u.LastName };
var query2 = from gm in userDb.GroupMembers
join ug in userDb.UserGroups on gm.GroupID equals ug.GroupID
join u in userDb.Users on gm.UserName equals u.UserName
where ug.GroupName == "AP Department" || ug.GroupName == "MIS"
orderby new { u.LastName, u.FirstName }
select new { UserName = u.UserName, FirstName = u.FirstName, LastName = u.LastName };
var query3 = query1.Concat(query2);
var users = new List<string> { };
users.AddRange(query3.Select(entry => entry.UserName));
//Dropdown lists being created and using a viewbag to setup and communication line between the the conroller and view
var warehouseList = new SelectList(whses);
ViewBag.WarehouseList = warehouseList;
var companyList = new SelectList(coNames);
ViewBag.CompanyList = companyList;
var pastDueList = new SelectList(new[]{"Yes", "No"});
ViewBag.PastDueList = pastDueList;
var usersList = new SelectList(users);
ViewBag.UsersList = usersList;
var openCompList = new SelectList(new[] { "Open", "Completed" });
ViewBag.OpenCompList = openCompList;
var sortByList = new SelectList(new[] { "Task ID", "Warehouse", "Assigned To", "PO Number", "Task Date" });
ViewBag.SortByList = sortByList;
tasks = GetFilteredSortedTasks(db,company, warehouse, pastDue, assignedToBy, openco, sortBy, poNumber,
freightNumber, vendorName, beginIssueDate, endIssueDate, beginInvoiceDate, endInvoiceDate,
beginCompletedDate, endCompletedDate).ToPagedList(pageIndex, pageSize);
return View(tasks);
}
Html.PagedListPager can take an additional parameter that is an expression that tells it how to generate the URL for the next page:
#Html.PagedListPager((IPagedList)ViewBag.OnePageOfItems, page => SomeMethodToGetUrlFor(page))
What you need to do basically is keep the current URL of the page (with all the appropriate querystring params for the filters and such) and add or update a page parameter. The "add or update" part makes this tricky, though: for example, you can't just tack on &page=N to the end of the URL as page may already be present in the querystring. I created a UrlHelper extension for just this purpose:
public static string ModifyQueryString(this UrlHelper helper, string url, NameValueCollection updates, IEnumerable<string> removes)
{
NameValueCollection query;
var request = helper.RequestContext.HttpContext.Request;
if (string.IsNullOrWhiteSpace(url))
{
url = request.Url.AbsolutePath;
query = HttpUtility.ParseQueryString(request.QueryString.ToString());
}
else
{
var urlParts = url.Split('?');
url = urlParts[0];
if (urlParts.Length > 1)
{
query = HttpUtility.ParseQueryString(urlParts[1]);
}
else
{
query = new NameValueCollection();
}
}
updates = updates ?? new NameValueCollection();
foreach (string key in updates.Keys)
{
query.Set(key, updates[key]);
}
removes = removes ?? new List<string>();
foreach (string param in removes)
{
query.Remove(param);
}
if (query.HasKeys())
{
return string.Format("{0}?{1}", url, query.ToString());
}
else
{
return url;
}
}
What this does is essentially let you pass in a NameValueCollection of parameters you want to add or update and/or a list of parameters you want to remove from the querystring. By default, it uses the current request URL, but if you pass in a URL it will do the transformation on that instead. Finally, it returns the modified URL back to the view.
I also added some additional methods to make working with this a little easier such as:
public static string UpdateQueryParam(this UrlHelper helper, string param, object value)
{
return ModifyQueryString(helper, new NameValueCollection { { param, value.ToString() } }, null);
}
public static string UpdateQueryParam(this UrlHelper helper, string url, string param, object value)
{
return ModifyQueryString(helper, url, new NameValueCollection { { param, value.ToString() } }, null);
}
So, if I just need to add/update one parameter, I don't need to actually instantiate a new NameValueCollection in my view.
Using these extensions, then, you can modify the URL appropriately with:
Url.UpdateQueryParam("page", page)
Which makes your pager line:
#Html.PagedListPager((IPagedList)ViewBag.OnePageOfItems, page => Url.UpdateQueryParam("page", page))
Related
Good Evening,
I'm trying to upload a file and when the form submits I just want to reload the partial view in the modal div, not the entire page. I looked at a number of other posts and they suggested to use AJAX but even when I used AJAX, instead of just reloading the partial view popup, It takes me to a full page view of the Partial View. I want to just reload the content inside of the modal div.
Here is my code:
Controller
public PartialViewResult FileUpload(int jobID)
{
ViewBag.jobID = jobID;
return PartialView(GetFiles(jobID));
}
[HttpPost]
public ActionResult FileUpload(int jobID, HttpPostedFileBase files)
{
int id = Convert.ToInt32(Session["id"]);
String FileExt = Path.GetExtension(files.FileName).ToUpper();
if(FileExt == ".PDF")
{
Stream str = files.InputStream;
BinaryReader Br = new BinaryReader(str);
Byte[] FileDet = Br.ReadBytes((Int32)str.Length);
UploadFileModel Fd = new UploadFileModel();
Fd.FileName = files.FileName;
Fd.FileContent = FileDet;
Fd.personID = id;
Fd.jobID = jobID;
file fileDB = new file();
fileDB.FileContent = Fd.FileContent;
fileDB.FileName = Fd.FileName;
fileDB.personID = id;
fileDB.jobID = Fd.jobID;
db.files.Add(fileDB);
db.SaveChanges();
return PartialView("FileUpload", GetFiles(jobID));
}
else
{
ViewBag.FileStatus = "Invalid file format.";
return PartialView();
}
}
[HttpPost]
public FileResult DownloadFile(int? fileId)
{
byte[] bytes;
string fileName, contentType;
var file = db.files.Find(fileId);
bytes = (byte[])file.FileContent;
fileName = file.FileName;
return File(bytes, fileName);
}
public List<UploadFileModel> GetFiles(int jobID)
{
List<UploadFileModel> files = new List<UploadFileModel>();
var filesDB = db.files.Where(x => x.jobID == jobID);
foreach (var fileDB in filesDB)
{
files.Add(new UploadFileModel
{
id = fileDB.id,
FileName = fileDB.FileName,
personID = fileDB.personID,
jobID = fileDB.jobID
});
}
return files;
}
Partial View:
#model IEnumerable<Church_Musician_Administration_App__Updated_.Models.UploadFileModel>
<style>
.table-striped tbody tr:nth-of-type(odd) {
background-color: rgb(222, 178, 241);
}
.table-striped tbody tr:nth-of-type(even) {
background-color: rgb(233, 204, 246);
}
#fileTable {
font-family: "Arial";
}
#fileTable tr {
cursor: default;
}
a:link {
color: darkviolet;
background-color: transparent;
text-decoration: none;
}
a:visited {
color: gray;
background-color: transparent;
text-decoration: none;
}
a:hover {
color: white;
background-color: transparent;
text-decoration: none;
}
a:active {
color: rebeccapurple;
background-color: transparent;
text-decoration: none;
}
</style>
#using (Html.BeginForm("FileUpload", "App", FormMethod.Post, new { enctype = "multipart/form-data", id="fileUploadForm"}))
{
<input type="hidden" name="jobID" value="#ViewBag.jobID" />
<label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" name="files" type="file" style="display:none"
onchange="$('#upload-file-info').text(this.files[0].name)">
Choose File
</label>
<span class='label label-info' id="upload-file-info">No File Uploaded</span>
<input class="btn btn-primary" type="submit" id="btnUpload" value="Upload" style="margin-bottom:5px" />
}
#using (Html.BeginForm("DownloadFile", "App", FormMethod.Post))
{
<input type="hidden" id="hfFileId" name="FileId" />
<input type="submit" id="btnDownload" value="Download" style="display:none" />
}
<hr />
<table id="fileTable" class="table table-striped" style="width:100%; border: 1px solid rgba(0,0,0,.125); border-left:none; border-right:none; text-align: center; display:inline-table;">
<tbody>
<tr style="background-color:darkviolet; height:40px; width:100%">
<th style="display:none;">JobID</th>
<th style="display:none">File ID</th>
<th style="color:white; border: 1px solid rgba(0,0,0,.125);">File Name</th>
<th style="color:white; border: 1px solid rgba(0,0,0,.125);">Download</th>
</tr>
#if (Model.Count() > 0)
{
foreach (var file in Model)
{
<tr>
<td style="display:none;">#file.id</td>
<td style="border: 1px solid rgba(0,0,0,.125);">#file.FileName</td>
<td style="border: 1px solid rgba(0,0,0,.125);">Download</td>
</tr>
}
}
else
{
<tr>
<td colspan="3"> </td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
function DownloadFile(fileId) {
$("#hfFileId").val(fileId);
$("#btnDownload")[0].click();
};
</script>
<script>
$('#btnUpload').click(function (event) {
event.preventDefault();
event.stopImmediatePropagation();
$('#fileUploadForm').submit();
$.ajax({
url: '/App/FileUpload',
type: 'POST',
success: function (data) {
$("#addMusicModalBodyDiv").html(data);
$("#addMusicModal").modal("show");
}
});
});
</script>
EDIT: Here is the code for where the addMusicModal is defined. It's located in a view called ViewSubstituteJobs
<button type="button" class="btn btn-primary" id="addMusic" onclick="addMusic()">Add Music</button>
<div class="modal" tabindex="-1" id="addMusicModal">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Music</h5>
<button type="button" class="close" aria-label="Close" id="closeAddMusicModal" onclick="closeDialog()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="addMusicModalBodyDiv">
</div>
</div>
</div>
</div>
var addMusic = function () {
var idFromTable = $("#subJobs tr").closest('tr.highlight').find('td:eq(0)').text();
if (idFromTable == 0) {
return false;
}
$.ajax({
type: "GET",
url: "/App/FileUpload",
data: {
jobID: idFromTable,
},
success: function (response) {
$(".modal").modal("hide");
$("#addMusicModalBodyDiv").html(response);
$("#addMusicModal").modal("show");
}
})
}
</script>
The following unhandled user exception is showing when fetching a list.
System.Data.Entity.Core.EntityCommandExecutionException: 'The data reader is incompatible with the specified 'EE_PlacementCellModel.PlacedCandidateList'. A member of the type, 'DriveDate', does not have a corresponding column in the data reader with the same name.'
The exception is shown in the last return code:
Placement.Context.cs
public virtual ObjectResult<PlacedCandidateList> PlacedCandidateList(Nullable<int> mstID, Nullable<int> cmpID)
{
var mstIDParameter = mstID.HasValue ?
new ObjectParameter("MstID", mstID) :
new ObjectParameter("MstID", typeof(int));
var cmpIDParameter = cmpID.HasValue ?
new ObjectParameter("CmpID", cmpID) :
new ObjectParameter("CmpID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<PlacedCandidateList>("PlacedCandidateList", mstIDParameter, cmpIDParameter);
}
Other related codes are given below:
ReportController.cs
public ActionResult PlacedCandidateList(string MstID, string CmpID)
{
int driveID = 0;
int companyID = 0;
if (MstID != "")
driveID = Convert.ToInt32(MstID);
if (CmpID != "")
companyID = Convert.ToInt32(CmpID);
ViewBag.Status = Db.Status.ToList();
var List = Db.PlacedCandidateList(driveID, companyID);
return Json(List.ToList(), JsonRequestBehavior.AllowGet);
}
public ActionResult PlacedCandidate()
{
ViewBag.Drive = Db.DriveMasters.Where(a => a.Isdeleted == false).ToList();
ViewBag.Company = Db.Companies.Where(a => a.Isdeleted == false).ToList();
return View();
}
[HttpPost]
public ActionResult PlacedCandidate(CandidateList candidate)
{
ViewBag.Drive = Db.DriveMasters.Where(a => a.Isdeleted == false).ToList();
ViewBag.Company = Db.Companies.Where(a => a.Isdeleted == false).ToList();
if (candidate.CompanyID == null)
candidate.CompanyID = 0;
if (candidate.DriveMasterID == null)
candidate.DriveMasterID=0;
List<PlacedCandidateList> CSL = new List<PlacedCandidateList>();
CSL = Db.PlacedCandidateList(candidate.DriveMasterID, candidate.CompanyID).ToList();
WebGrid grid = new WebGrid(source: CSL, canPage: false, canSort: false);
string gridhtml = grid.GetHtml(
columns: grid.Columns(
grid.Column("SerailNo", "Serail No"),
grid.Column("StudentName", "Student Name"),
grid.Column("DriveName", "Drive Name"),
//grid.Column("DriveDate", "Drive Date"),
grid.Column("CompanyName", "Company Name"),
grid.Column("PositionName", "Position Name")
)).ToString();
string exportdata = string.Format("<html><head>{0}</head><body>{1}</body></html>", "<style>table {border-collapse: collapse; width: 100%; border: 1px solid #ddd;} th, td {text-align: left;padding: 8px; width:100px; border-bottom: 1px solid #ddd;} tr:nth-child(even){background-color: #f2f2f2} th {background-color: #4CAF50; color: white;} </style>", gridhtml);
var bytes = System.Text.Encoding.UTF8.GetBytes(exportdata);
using (var input = new MemoryStream(bytes))
{
var output = new MemoryStream();
var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
var writer = PdfWriter.GetInstance(document, output);
writer.CloseStream = false;
document.Open();
var xmlworker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
xmlworker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
document.AddTitle("Placed Candidates");
document.AddCreationDate();
document.Close();
output.Position = 0;
return new FileStreamResult(output, "application/pdf");
}
}
PlacedCandidateList.cs
/------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PlacementCell.Models
{
using System;
public partial class PlacedCandidateList
{
public Nullable<long> SerailNo { get; set; }
public int CandidatesListID { get; set; }
public string CompanyName { get; set; }
public string PositionName { get; set; }
public string StudentName { get; set; }
public string DriveName { get; set; }
public string Status { get; set; }
public int StatusID { get; set; }
public string DriveDate { get; set; }
}
}
PlacedCandidate.cshtml
#model PlacementCell.Models.CandidateList
#{
ViewBag.Title = "Placed Candidate";
}
#using (Html.BeginForm("PlacedCandidate", "Report", FormMethod.Post, new { enctype = "multipart/form-data", name = "candidate", id = "candidate" }))
{
<div class="callout bg-gray-light">
<div class="row">
<div class="col-xs-2 col-md-1"><div class="btn btn-app btn-twitter"><i class="glyphicon glyphicon-print"></i>Print</div></div>
</div>
</div>
<section class="content-header">
<h1>
Placed Candidates
<small>Report</small>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-list-alt"></i> Report</li>
<li class="active"><i class="fa fa-circle-o"></i> Placed Candidates</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="box">
<div class="box-body">
<br />
<div class="row">
<div class="col-xs-12 col-md-6">
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6"> Placement Drive</div>
<div class="col-md-6">
#Html.DropDownListFor(model => model.DriveMasterID, new SelectList(ViewBag.Drive, "DriveMasterID", "DriveName"), "Select Drive", new { #class = "form-control", #Onchange = " GetVariables();" })
</div>
</div>
<div class="form-group">
<div class="col-md-6">Company</div>
<div class="col-md-6">
#Html.DropDownListFor(model => model.CompanyID, new SelectList(ViewBag.Company, "CompanyID", "CompanyName"), "Select Company", new { #class = "form-control", #Onchange = " GetVariables();" })
</div>
</div>
<div class="form-group">
<div class="col-md-6"></div>
<div class="col-md-6">
Find
</div>
</div>
</div>
</div>
</div>
<div class="row">
<table class="table table-bordered table-hover dataTable">
<thead>
<tr>
<th>
<input type="checkbox" class="checkbox" />All
</th>
<th>
Sl.
</th>
<th>
Company Name
</th>
<th>
Drive Name
</th>
<th>
Drive Date
</th>
<th>
Position Name
</th>
<th>
Student Name
</th>
<th>
</th>
</tr>
</thead>
<tbody id="drive">
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
}
#section scripts
{
<script type="text/javascript">
function GetList() {
var MstID = document.getElementById("DriveMasterID").value;
var CmpID = document.getElementById("CompanyID").value;
//alert(MstID);
$.ajax({
url: '/Report/PlacedCandidateList',
type: "GET",
data: { MstID: MstID, CmpID: CmpID },
dataType: "JSON",
success: function (List) {
//alert("ffffg");
$("#drive").html(""); // clear before appending new list
//alert("ff");
var k = 10;
var j = 1;
$.each(List, function (i, vari) {
var Qun = "arr" + k;
var ErrorQun = "arre" + k;
var chbbx = '<tr id="checkboxes"><td><input type="checkbox" name="CandidatesListID" id=' + k + ' class="checkbox" value=" ' + vari.CandidatesListID + '" checked="checked" disabled="disabled" /></td><td> ' + j + ' </td><td> ' + vari.CompanyName + ' </td><td> ' + vari.DriveName + ' </td><td> ' + vari.DriveDate + '</td><td> ' + vari.PositionName + ' </td><td> ' + vari.StudentName + ' </td><td> ' + vari.Status + '</td></tr>';
$("#drive").append(
$(chbbx));
k++;
j++;
//alert(place.Place1);
}
);
},
error: function (List) {
alert("No Data Found");
$("#drive").html("");
}
});
}
</script>
}
Hi I am developing application where i have 5 textboxes and search button. When i enter data into textbox and click on search, corresponding matched data of database will be displayed in below table. I have implemented paging and it works fine. Below is the code.
[HttpGet]
public ActionResult Index(int? clientId, string dateofAction, int? doc_typeid, string employeeID,string citizenId,int? currentFilter, string filterdateTime,int? filterdocType,string filteredemployeeID,string filteredcitizenId,int? page)
{
ViewBag.curpageNumber = page;
logDetailsEnumeration model = new logDetailsEnumeration();
DB_KYC3Entities db = new DB_KYC3Entities();
var docTypes = from c in db.tm_doc_type select c;
if (clientId != null)
{
page = 1;
}
else
{
clientId = currentFilter;
}
if(dateofAction!=null)
{
page = 1;
}
else
{
dateofAction = filterdateTime;
}
if(doc_typeid != null)
{
page = 1;
}
else
{
doc_typeid = filterdocType;
}
if(employeeID!=null)
{
page = 1;
}
else
{
employeeID = filteredemployeeID;
}
if(citizenId!=null)
{
page = 1;
}
else
{
citizenId = filteredcitizenId;
}
ViewBag.CurrentFilter = clientId;
ViewBag.filterdateTime = dateofAction;
int pageSize = 8;
int pageNumber = (page ?? 1);
VerificationLogBAL obj = new VerificationLogBAL();
int docType = obj.GetDocDetails(doc_typeid?? default(int));
List<logDetails> logDetails = obj.getlogDetails(clientId?? default(int), dateofAction, docType, employeeID, citizenId);
IPagedList<logDetails> pagedLog = logDetails.ToPagedList(pageNumber, pageSize);
model = new logDetailsEnumeration()
{
pageNum= pageNumber,
doc_typeid = doc_typeid,
Count=logDetails.Count,
employeeID = employeeID,
citizenId= citizenId,
logDetails = pagedLog,
doctype_name=new SelectList(docTypes, "doc_typeid", "doctype_name")
};
return View("Index",model);
}
}
This is my view code.
#using (Html.BeginForm("Index", "VerificationLog", FormMethod.Get))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="message"></div>
<div class="loginUsernamePassword">
<i class="fa fa-user"></i>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="dataTable tableHover">
<tr>
<th width="8%" scope="col">Client ID</th>
<th width="20%" scope="col">
<div class="form-box form-box-default">
#Html.TextBoxFor(x=>x.clientId, ViewBag.CurrentFilter as string, new { #id = "clientId", #placeholder = "Client ID", #class = "form-control", #maxlength = 20 })
</div>
</th>
<th width="10%" scope="col">Date Of Action</th>
<th width="20%" scope="col">
<div class="form-box form-box-default">
#Html.TextBoxFor(x=>x.dateofAction, ViewBag.filterdateTime as string, new { #id = "dateofAction", #placeholder = "Date Of Action", #class = "txtBox form-control calender validate[required]" })
#*#Html.TextBox("dateofAction", ViewBag.filterdateTime as string, new { #id = "dateofAction", #placeholder = "Date Of Action", #class = "txtBox form-control calender validate[required]" })*#
</div>
</th>
<th width="15%" scope="col">Type Of Document</th>
<th width="17%" scope="col">
<div class="form-box form-box-default">
#*#Html.TextBox("typeofDocument", ViewBag.filterdateTime as string, new { #id = "typeofDocument", #placeholder = "Type Of Document", #class = "form-control", #maxlength = 20 })*#
#Html.DropDownListFor(x=>x.doc_typeid,Model.doctype_name,"Select",new { #class = "form-control" })
</div>
</th>
</tr>
<tr>
<th width="15%" scope="col">Employee ID</th>
<th width="17%" scope="col">
<div class="form-box form-box-default">
#Html.TextBoxFor(x=>x.employeeID, Model.employeeID, new { #id = "employeeID", #placeholder = "Employee ID", #class = "form-control", #maxlength = 20 })
</div>
</th>
<th width="15%" scope="col">Citizen ID</th>
<th width="17%" scope="col">
<div class="form-box form-box-default">
#Html.TextBoxFor(x=>x.citizenId, Model.citizenId, new { #id = "citizenId", #placeholder = "Citizen ID", #class = "form-control", #maxlength = 20 })
</div>
</th>
<th width="10%" scope="col" colspan="2">
<input type="submit" value="Search" class="btn btn-primary btn-cons search" />
</tr>
</table>
</div>
}
</div>
#if (Model != null && Model.logDetails.Count != 0)
{
<br />
<h2>Verification Log</h2>
<br />
<div id="GridDetails">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="dataTable tableHover">
<tr>
#*<th>#Html.ActionLink("Label", "Index", new { sortOrder = ViewBag.LabelSortParm, currentFilter = ViewBag.CurrentFilter, filterdateTime = ViewBag.filterdateTime, filterdocType = Model.doc_typeid, filteredemployeeID = Model.employeeID, filteredcitizenId = Model.citizenId, Page = ViewBag.curpageNumber })</th>*#
<th>Label</th>
<th>Value</th>
<th>UpdatedOn</th>
<th>UpdatedBy</th>
<th>UpdatedStatus</th>
<th>RejectComment</th>
</tr>
#foreach (var group in Model.logDetails)
{
<tr>
<td>#group.contentLabel</td>
<td>#group.contentValue</td>
<td>#group.updatedOn</td>
<td>#group.updatedBy</td>
<td>#group.updatedStatus</td>
<td>#group.rejectComment</td>
</tr>
}
</table>
#Html.PagedListPager(Model.logDetails, page => Url.Action("Index",
new { page, currentFilter = ViewBag.CurrentFilter, filterdateTime=ViewBag.filterdateTime, filterdocType= Model.doc_typeid, filteredemployeeID = Model.employeeID, filteredcitizenId = Model.citizenId }))
Page #(Model.logDetails.PageCount < Model.logDetails.PageNumber ? 0 : Model.logDetails.PageNumber) of #Model.logDetails.PageCount
</div>
I am having problem in displaying message No records found. If i try to put No records found by checking following property if(Model!=null) then When the first time page loads then also it display No records found. I want to display only after clicking on submit button and if there are no matching records found. Is there any way I can implement solution in above scenario? Thanks
You could add a new property to the model that would only be set when the search has been completed. This would indicate if there were no records found and you could use logic in the view to display an appropriate message.
I need to show any xml in table in my mvc app like in photo
https://drive.google.com/file/d/0B9JoyO0mTmhnNWplMlR6ME5PeW8/edit?usp=sharing
this is my code but it work only for one parent element in xml
enter code here String f1 = Session["doc2"].ToString();
Value model2 = new Value();
HttpPostedFileBase file2 = TempData["doc3"] as HttpPostedFileBase;
var fileex = Path.GetExtension(file2.FileName);
string xmlstr = ".xml";
string strall = "";
XDocument xml = XDocument.Parse(f1);
var abc = xml.Root.DescendantNodes().OfType<XElement>()
.Select(x => x.Name).Distinct();
ViewBag.MyListabc = abc;
var abcd = xml.Root.DescendantNodes().OfType<XElement>()
.Select(x => x.Value).Distinct();
ViewBag.MyListabcd = abcd;
model2 = new Value()
{
file1 = abc
};
//ViewBag.MyList = listelem;
return View(model2);
}
And this is my view
enter code here<table style="font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;">
#foreach (var item in ViewBag.MyListabc)
{
<th style="border: 1px solid; width:80px"> #Html.DisplayTextFor(x => item) </th>
}</tr>
#foreach (var item in ViewBag.MyListabcd)
{
<td style="border: 1px solid; width:80px">
#Html.DisplayTextFor(x => item) </td>
}</tr>
</table>
You could parse your xml table to a DataTable object and then render your DataTable in your view. Some links for inspiration.
Displaying standard DataTables in MVC
http://weblogs.asp.net/gunnarpeipman/archive/2011/11/19/asp-net-mvc-simple-view-to-display-contents-of-datatable.aspx
I try to add my files into DropDownList, all my files with the relevant property already return by the controller:
// GET: /WebMail/
public ActionResult Index()
{
var fileNameList = db.Captures.ToList().Where(x => x.robotFamily == "WebMail");
//return View(db.Captures.ToList().Where(x => x.robotFamily == "WebMail"));
ViewBag.Files = fileNameList;
return View();
}
Index.cshtml
#model IEnumerable<AutomationCapturesMVC.Models.Capture>
#{
//ViewBag.Title = "Index";
}
<table class="table">
<tr>
<th style="font-size: 20px">
#Html.DisplayNameFor(model => model.fileName)
</th>
<th></th>
</tr>
#Html.DropDownList("Id", (IEnumerable<AutomationCapturesMVC.Models.Capture>)ViewBag.Files, new { id = "WebMail", #class = "btn dropdown-toggle" })
#foreach (var item in Model)
{
<tr>
<td style="font-size: 15px">
#Html.DisplayFor(modelItem => item.fileName)
</td>
<td>
#Html.ActionLink("File Details", "Details", new { id = item.id })
</td>
</tr>
}
</table>
this is my page error:
http://s21.postimg.org/983eokpfq/1231231313.jpg
How about the following?
In controller
public ActionResult Index()
{
var fileNames = GetDatabaseFileNames();
var fileNameList = fileNames.Select(d => new SelectListItem { Text = d.FileName, Value = d.FileName.ToString() }).ToList();
ViewBag.Files = fileNameList;
return View();
}
In View
#Html.DropDownList("DatabaseFiles", (IEnumerable<SelectListItem>)ViewBag.Files, new { id = "DatabaseFiles", #class = "btn dropdown-toggle" })