I am trying to achieve the task of binding a dataset to a webgrid.
As per my knowledge, Webgrid accepts only model as datasource. But I need to acheive it using a dataset. I have created a Dataset property on the model itself.
Please do guide me. I am a newbie.
TIA
The WebGrid is not able to extract data from a dataset (or more properly, as datatable). You can use LINQ to DataSet to transform your data an IEnumerable. Borrowing the DataTable example from Dotnet Perls, here's how you might do that:
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
var data = table.AsEnumerable().Select(r => new {
Dosage = r.Field<int>("Dosage"),
Drug = r.Field<string>("Drug"),
Patient = r.Field<string>("Patient"),
Date = r.Field<DateTime>("Date")
});
var grid = new WebGrid(data);
Related
I am having trouble with stored value on TempData, Actually I am learning behavior of TempData and tried with some workable example from various sites.Here is problem : I opening my context file after some linq operation I am saving it to my variable , I used Breakpoint to inspect data,But data is not in TempData. Please can anyone tell me where data will be stored such that I can inspect it using breakpoint of Visual studio.Below is my code
public ActionResult Index()
{
ReadContext db = new ReadContext();
var lst = (from p in db.data1
join f in db.data2
on p.ID equals f.ID
select new
{
Sr = p.Sr,
Group = p.Group,
ID=p.ID,
CompanyName = f.CompanyName
}).ToList()
.Select(x => new dataViewModel()
{
ID=x.ID,
Sr = x.Sr,
Group = x.Group,
CompanyName = x.CompanyName
});
TempData["l1"] = lst;
return View(lst);
}
Including output as image(first beakpoint at Var) ![1]:https://imgur.com/osY345F
Second Breakpoint at TempData ![2]:https://imgur.com/5oIDN9e which is showing me null value is on TempData. What I need to do to see values are visible in breakpoint.
The default TempData provider uses cookies. In order to store an object in TempData you need to serialize it first.
TempData["l1"] = JsonConvert.SerializeObject(lst); //using Newtonsoft.Json;
The amount of data stored in TempData should be minimized. Rather than storing entire records in TempData I would recommend just storing a list of IDs.
Does the application use TempData only sparingly, for relatively small
amounts of data (up to 500 bytes)? If so, the cookie TempData provider
will add a small cost to each request that carries TempData. If not,
the session state TempData provider can be beneficial to avoid
round-tripping a large amount of data in each request until the
TempData is consumed.
[Introduction to session and application state in ASP.NET Core][https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?tabs=aspnetcore2x#tempdata]
var lst = (from p in db.data1
join f in db.data2
on p.ID equals f.ID
select new
{
Sr = p.Sr,
Group = p.Group,
ID=p.ID,
CompanyName = f.CompanyName
}).ToList()
.Select(x => new dataViewModel()
{
ID=x.ID,
Sr = x.Sr,
Group = x.Group,
CompanyName = x.CompanyName
}).ToList();
I'm very first experience in ASP.NET MVC and after I read through a few articles I decided I try my new project with MVC.
And I used ADO.net entity data model and I created Create/ Delete/ Details/ Edit/ Index. It works fine.
So I plan to improve in user interface because some of the fields are comes from another databases such as HR Database, etc... for employee information.
for e.g : to choose Employee's Name on my form, I have to use DropDownList and that data comes from another database, HR as I mentioned in above. I have no idea how to access difference database in one model and here I asked How to solve multiple databases in one edmx for ASP.net MVC?
However I tried to create one more model for the other database and try to join with Linq.
//
// GET: /ARS/
public ActionResult Index()
{
var employee = new List<EMPLOYEE>(chr.EMPLOYEEs);
var reqform = new List<RequestForm>(ars.RequestForms.Include(r => r.Genre));
var requestforms = from r in reqform
join e in employee on r.PrjDeptMgr equals e.EmployeeID
select new
{
r.FormID,
r.GenreID,
r.JobNo,
r.Description,
r.StartDate,
r.EndDate,
r.PrjDeptMgr,
r.IsAgreed,
r.Genre
};
//var requestforms = ars.RequestForms.Include(r => r.Genre);
return View(requestforms.ToList());
}
But I got this error
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType29[System.Int32,System.Int32,System.String,System.String,System.DateTime,System.DateTime,System.String,System.Boolean,Access_Request_System.Models.Genre]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Access_Request_System.Models.RequestForm]'.
Really no idea for this case... Please!
Your view file requires IEnumerable<RequestForm>, but the type you're passing does not match the required type (it's anonymous).
Try the following changes.
List<RequestForm> requestforms = (from r in reqform
join e in employee on r.PrjDeptMgr equals e.EmployeeID
select new RequestForm
{
FormID = r.FormID,
Genre = r.GenreID,
JobNo = r.JobNo,
Description = r.Description,
StartDate = r.StartDate,
EndDate = r.EndDate,
PrjDeptMgr = r.PrjDeptMgr,
IsAgreed = r.IsAgreed,
Genre = r.Genre
}).ToList();
return View(requestForms);
SITUATION
I am using Trirand JQGrid for MVC[server side] in my proj.
I've got more than 5 hundred thousand records in a single table.
I load the data by calling this piece of code. this is what gives 500000 records collection.
IEnumerable<myIndexViewModel> myviewmodel= _allincidents.Select(x => new myIndexViewModel
{
IncidentRequestStatus = x.RequestStatus,
RequestByUserName = x.RequestByUserName,
Subject = x.Subject
});
gridModel.JqGrid.DataBind(myviewmodel.AsQueryable());
JQgrid handles the json based ajax requests very nicely for every next page i click.
PROBLEM
I dont want to load 5 hundred thousand records all together on the page load event as it kills jqgrid.
If i write a stored procedure in the DB for requesting a specific page to be displayed then its gonna load only that page in the myviewmodel collection.
How do i get pages on the fly from the DB when the next page is clicked. is this even possible in jqgrid?
SITUATION 2
Based on the answers from VIJAY and MARK the approach they have shown is absolutely correct but over here the JQGRID for MVC sets up the DATAURL property for making the method call. In this case its the IncidentGridRequest.
How do i send in the page number when the grid next page or previous page is clicked?
incidentModel.IncidentGrid.DataUrl = Url.Action("IncidentGridRequest")
public JsonResult IncidentGridRequest()
{
}
Your controller action that will provide your grid with results can accept some extra information from jqGrid.
public ActionResult GetGridData(string sidx, string sord, int page, int rows, bool _search, string filters)
The main parts you are interested in is the page, rows (sidx is for column sorting, sord for the sorting order, _search if there was a search done on the grid, and if so filters contains the search information)
When you generate your results you should be able to then
IEnumerable<myIndexViewModel> myviewmodel = allincidents.Select(x => new myIndexViewModel
{
IncidentRequestStatus = x.RequestStatus,
RequestByUserName = x.RequestByUserName,
Subject = x.Subject
}).Skip((page - 1) * rows).Take(rows)
PS. I'm not sure if you using IEnumberable will be moving a large amount of data from your DB but you might want to use IQueryable when you generate this subset of data for the jqGrid.
Edit: To deal with your paging issues, You should be calculating the number of total records in your query and passing that value to the grid, Ex
int totalRecords = myviewmodel.Count();
and then later you would pass that to your grid as a jSon value. Ex
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
userdata = new {SearchResultsFound = searchResultsFound},
rows = (
......
Yes, for example if you are accepting the page number you want to turn to in a variable named page and the have the size of page in a variable pageSize then:
IEnumerable<myIndexViewModel> myviewmodel = allincidents.Select(x => new myIndexViewModel
{
IncidentRequestStatus = x.RequestStatus,
RequestByUserName = x.RequestByUserName,
Subject = x.Subject
}).Skip((page-1)*pageSize).Take(pageSize));
will give you the records of size pageSize to you.
The Trirand jqGrid for ASP.NET MVC is using IQueryable interface inside the JqGrid.DataBind() method to implement pagin, sorting and filtering.
So the key here is to use datasource, which handle these types of operations at the database level (by crafting SQL queries to the database in such a way that only the data required is fetched). All major ORMs have this support, this includes: LINQ-2-SQL, Entity Framework, NHbiernate, LLBLGen.
You just need to use one of this technologies, and past the required context directly to JqGrid.DataBind() method (without extracting the data manually like you do it in your sample).
An easier approach by using PagedList library (from Nuget). There is a useful blog by Joseph Schrag
public JsonResult Users(int PageNo, int Rows)
{
var UserList = db.Users.Select(t => new
{
t.UserId,
t.Username,
t.Firstname,
t.Lastname,
t.Designation,
t.Country,
t.Email
}).OrderBy(t => t.UserId);
var pagedUserList = UserList.ToPagedList(PageNo, Rows);
var results = new
{
total = pagedUserList.PageCount, //number of pages
page = pagedUserList.PageNumber, //current page
records = UserList.Count(), //total items
rows = pagedUserList
};
return new JsonResult() { Data = results, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
i am designing a asp.net mvc project. i want to convert my document into pdf.
i am using itextsharp-all-5.1.1 for this conversion.
i created object as
PdfWriter.GetInstance(doc, new FileStream((Request.PhysicalApplicationPath + "\\1.pdf"), FileMode.Create));
now i want to add the result of following query in doc object, so how can i add the result of this queryin doc object.
i have this query:-
var vv= (from x in db.RawMaterial join y in db.ProductFormulation on x.ID equals y.RawMaterialID where y.ProductID == 1 select new { x.Description, y.Quantity });
please help me please...
So, if I understand you correctly you are creating a PDF file using itextsharp and you want to add to this pdf file the result of some query which is a collection of some item that contains a description and a quantity.
If this is the case I wonder why your question is tagged with asp.net-mvc as this has nothing to do with it. It's itextsharp problem. Here's a nice example illustrating how to create a PDF document containing a table.
So for your query you could adapt it like this:
var vv =
from x in db.RawMaterial
join y in db.ProductFormulation
on x.ID equals y.RawMaterialID
where y.ProductID == 1
select new { x.Description, y.Quantity };
var table = new PdfPTable(2);
table.AddCell("Description");
table.AddCell("Quantity");
foreach (var item in vv)
{
table.AddCell(item.Description);
table.AddCell(item.Quantity);
}
doc.Add(table);
My problem is pretty simple. Lets say I have a dropdown with users.
in the database i have 3 fields for my user table:
user_id
user_name
user_firstname
in my MVC app i want to link those users to projects. so thats why i want the dropdown.
now, i want to have a selectlist, with the ID as the value, and the firstname AND lastname to be the 'text'
SelectList sl = new SelectList(users, "user_id", "user_name");
now how do i get the first name also in the text? this should be fairly easy, but seems it isnt...
Use LINQ to transform your list of users into a list of SelectListItem.
var selectOptions =
from u in yourUserQuery
select new SelectListItem {
Value = u.user_id,
Text = u.user_firstname + " " + u. user_name
};
You can then convert that to a SelectList however you see fit. I personally like to define a .ToSelectList() extension method for IEnumerable<SelectListItem>, but to each his own.
You need to build a list from your database in the format you need. Here is what I did after my database read into a DataTable,
IList<UsrInfo> MyResultList = new List<UsrInfo>();
foreach (DataRow mydataRow in myDataTable.Rows)
{
MyResultList.Add(new UsrInfo()
{
Usr_CD = mydataRow["USR_NR"].ToString().Trim(),
Usr_NA = mydataRow["USR_NA_LAST"].ToString().Trim() + " , " +
mydataRow["USR_NA_FIRST"].ToString().Trim()
});
}
return new SelectList(MyResultList, "Usr_CD", "Usr_NA");