I am working on a project utilizing MVC4 and EF Data First in VS2013. I am getting this error when trying to pass my object to the view.
The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType34[System.String,System.Nullable1[System.Int32],System.Nullable1[System.Int32],System.Nullable1[System.Int32]]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[TitansMVCWithBootStrap.Models.Player_Game_Stats]'
I am not sure how to fix this, any suggest would help. Thanks
Controller
public class PlayerGameStatsController : Controller
{
private Context db = new Context();
// GET: PlayerGameStats/Details/5
public ActionResult Details(int gid=19, int sid = 11)
{
var playerGameStats = from pgs in db.PlayerGameStats
join p in db.Players on pgs.Player_id equals p.id_player
where pgs.SeasonId == 11 && pgs.GameNumber == 19
select new
{
p.PlayerName,
pgs.PlateAppearance,
pgs.Runs,
pgs.Hits
};
return View(playerGameStats);
}
Model
public class Player_Game_Stats
{
[Key]
[Column(Order = 0)]
public int Player_id { get; set; }
[Key]
[Column(Order = 1)]
public int GameNumber { get; set; }
public Nullable<int> PlateAppearance { get; set; }
public Nullable<int> Runs { get; set; }
public Nullable<int> HR { get; set; }
public int Hits{ get; set; }
//[ForeignKey("id_player")]
//public virtual Players Player { get; set; }
}
}
View
#model IEnumerable<TitansMVCWithBootStrap.Models.Player_Game_Stats>
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Details</h2>
<table class="table table-striped">
<tr>
<th>
#Html.DisplayNameFor(model => model.PlayerName)
</th>
<th>
#Html.DisplayNameFor(model => model.PlateAppearance)
</th>
<th>
#Html.DisplayNameFor(model => model.Runs)
</th>
<th>
#Html.DisplayNameFor(model => model.Hits)
</th>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.PlayerName)
</td>
<td>
#Html.DisplayFor(modelItem => item.PlateAppearance)
</td>
<td>
#Html.DisplayFor(modelItem => item.Runs)
</td>
<td>
#Html.DisplayFor(modelItem => item.Hits)
</td>
</tr>
}
</table>
Also tried
var playerGameStats = (from pgs in db.PlayerGameStats
join p in db.Players on pgs.Player_id equals p.id_player
where pgs.SeasonId == 11 && pgs.GameNumber == 19
select new Player_Game_Stats
{
p.PlayerName,
pgs.PlateAppearance,
pgs.Runs,
pgs.Hits
}).ToList();
return View(playerGameStats);
Try this:
public ActionResult Details(int gid=19, int sid = 11)
{
var playerGameStats = from pgs in db.PlayerGameStats
join p in db.Players on pgs.Player_id equals p.id_player
where pgs.SeasonId == 11 && pgs.GameNumber == 19
select new TitansMVCWithBootStrap.Models.Player_Game_Stats
{
PlayerName = p.PlayerName,
PlateAppearance = pgs.PlateAppearance,
Runs = pgs.Runs,
Hits = pgs.Hits
};
return View(playerGameStats);
}
Related
I want to build my view and join 2 tables using LINQ but i got this error in view in foreach in Model
#foreach (var item in Model)
This is my classes :
public partial class Lab_orders_Cash
{
[Display(Name = "Order Id")]
public int cash_order_id { get; set; }
[Display(Name = "Order Date")]
public Nullable<System.DateTime> order_date { get; set; }
[Display(Name = "MRN File No.")]
public Nullable<int> patient_no { get; set; }
public string invoice_order_no { get; set; }
public string order_description { get; set; }
public string user_id { get; set; }
[Display(Name = "Order Status")]
public Nullable<int> order_status { get; set; }
public Nullable<int> catid { get; set; }
public Nullable<int> almansoor { get; set; }
public Nullable<int> prio_id { get; set; }
}
public partial class Lab_Sample_status
{
public int status_id { get; set; }
public string status_name { get; set; }
}
this my controller :
public ActionResult ordersCash()
{
var OrdersList = from o in db.Lab_orders_Cash
Join os in db.Lab_Sample_status on o.order_status equals os.status_id into tablestatus
where o.patient_no == (int)Session["UserpatientNo"]
select o;
return View(OrdersList);
}
In view i used Tuples :
#using AljawdahNewSite.Models;
#model Tuple<Lab_orders_Cash,Lab_Sample_status>
#{
#{
ViewBag.Title = "ordersCash";
Layout = "~/Views/Shared/_LayoutPatients.cshtml";
}
<h2>Orders List </h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(Tuple => Tuple.Item1.cash_order_id)
</th>
<th>
#Html.DisplayNameFor(Tuple => Tuple.Item1.order_date)
</th>
<th>
#Html.DisplayNameFor(Tuple => Tuple.Item1.patient_no)
</th>
<th>
#Html.DisplayNameFor(Tuple => Tuple.Item2.status_name)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(Tuple => Tuple.Item1.cash_order_id)
</td>
<td>
#Html.DisplayFor(Tuple => Tuple.Item1.order_date)
</td>
<td>
#Html.DisplayFor(Tuple => Tuple.Item1.patient_no)
</td>
<td>
#Html.DisplayFor(Tuple => Tuple.Item2.status_name)
</td>
<td>
#Html.ActionLink("Details", "Details", new { id=item.cash_order_id })
</td>
</tr>
}
</table>
in foreach when select model i got this error , also i tried to use IEnumerable in view like this
#model Tuple<IEnumerable<Lab_orders_Cash>,IEnumerable<Lab_Sample_status>>
but same error when i select Model it shows the error
What i need to change to solve this error.
you can use another way like the following steps :
1- Create new class and put your tables in that class
public class Tables
{
public Lab_orders_Cash LabOrdersCash { get; set; }
public Lab_Sample_status LabOrderStatus { get; set; }
}
2- Write the controller like the following :
public ActionResult ordersCash()
{
List<Lab_orders_Cash> ordercash = db.Lab_orders_Cash.ToList();
List<Lab_Sample_status> samplestatus = db.Lab_Sample_status.ToList();
var OrdersList = from o in ordercash
join st in samplestatus on o.order_status equals st.status_id
where o.patient_no == (int)Session["UserpatientNo"]
select new Tables{ LabOrdersCash = o , LabOrderStatus = st };
return View(OrdersList);
}
3- Create your view use the following code :
#model IEnumerable<AljawdahNewSite.Models.Tables>
#{
ViewBag.Title = "ordersCash";
Layout = "~/Views/Shared/_LayoutPatients.cshtml";
}
<h2>Orders List</h2>
<table class="table">
<tr>
<td> Order No. </td>
<td> order date </td>
<td> Patient No </td>
<td> Status </td>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.LabOrdersCash.cash_order_id</td>
<td>#item.LabOrdersCash.order_date</td>
<td>#item.LabOrdersCash.patient_no</td>
<td>#item.LabOrderStatus.status_name</td>
</tr>
}
</table>
This way more effective and easily you can add all your tables in this tables class and call this class any where in your project and easier than Tuples.
i want to bind in list, how to do that, please see my code below
this below is my Controller
var transaction = await (from a in _context.Transaction group a by a.Nobukti into pg
join b in _context.ChartAccount on pg.FirstOrDefault().Kodeakun
equals b.Kodeakun
select new Transaksi
{
Nobukti = pg.FirstOrDefault().Nobukti,
Tanggal = pg.FirstOrDefault().Tanggal,
Keterangan = pg.FirstOrDefault().Keterangan,
Trans = pg.ToList()
}).ToListAsync();
return View(transaction);
See my Trans = pg.ToList() in Controller, inside pg.ToList() there are Kodeakun, and i want bind to Kodeakun = a.Kodeakun + b.Kodeakun
This below is my Model
public class ChartAccount
{
[Key]
public string Kodeakun { get; set; }
public string Namaakun { get; set; }
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal Saldo { get; set; }
}
public class Transaksi
{ [Key]
public int Iud { get; set; }
public int Id { get; set; }
public string Nobukti { get; set; }
public string Kodeakun { get; set; }
public string Keterangan { get; set; }
[DataType(DataType.Date)]
public DateTime Tanggal { get; set; }
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal Debit { get; set; }
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal Kredit { get; set; }
public virtual List<Transaksi> Trans { get; set; }
}
this below is my view
<table class="table">
#foreach (var item in Model)
{
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Nobukti) :
#Html.DisplayFor(modelItem => item.Nobukti)
</th>
<th>
#Html.DisplayNameFor(model => model.Keterangan) :
#Html.DisplayFor(modelItem => item.Keterangan)
</th>
<th>
#Html.DisplayNameFor(model => model.Tanggal) :
#Html.DisplayFor(modelItem => item.Tanggal)
</th>
</tr>
</thead>
<tbody>
#foreach (var transaksi in item.Trans)
{
<tr>
<td>
#Html.DisplayFor(modelItem => transaksi.Kodeakun)
</td>
<td>
#if (transaksi.Debit == 0) { }
else
{
#Html.DisplayFor(modelItem => transaksi.Debit)
}
</td>
<td>
#if (transaksi.Kredit == 0) { }
else
{
#Html.DisplayFor(modelItem => transaksi.Kredit)
}
</td>
</tr>
}
</tbody>
}
</table>
sorry for my bad english, i use ASP Net Core 2.2
This question already has answers here:
The model item passed into the dictionary is of type .. but this dictionary requires a model item of type
(7 answers)
Closed 5 years ago.
I get this Exception but i don't how to fix it:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[DataModel.Gabarit]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[ViewModel.GabaritViewModel]'.
My Controller:
public ActionResult Traitement(string designation)
{
GabaritRepository gabaritrepository = new GabaritRepository(db);
var gabarits = gabaritrepository.Get(g => g.Designation == designation).ToList();
return View(gabarits);
}
My View:
#model IEnumerable<ViewModel.GabaritViewModel>
#{
ViewBag.Title = "Traitement";
}
<h2>Traitement</h2>
<div class="col-xs-12">
<div class="box">
<h2>Gabarits</h2>
<table class="table table-striped">
<tr>
<th>
Code à barre
</th>
<th>
Etat
</th>
<th>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CodeBarre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Etat)
</td>
<td>
#Html.ActionLink("Sortie", "Sortie", new {id = item.CodeBarre})
</td>
</tr>
}
</table>
</div>
</div>
GabaritViewModel:
namespace ViewModel
{
public class GabaritViewModel
{
public int CodeBarre { get; set; }
public string Designation { get; set; }
public string Photo { get; set; }
public Nullable<int> Produit { get; set; }
public Nullable<int> Poste { get; set; }
public string Exemplaire { get; set; }
public string Etat { get; set; }
public int Id_Etat { get; set; }
}
I have to pass ViewModel not DataModel and I don't know why I'm not allowed to.
Your repositories .Get() method is returning a collection of type Garbarit, you need a collection of type GabaritViewModel.
One option would be to do another select and manually map your properties:
public ActionResult Traitement(string designation)
{
GabaritRepository gabaritrepository = new GabaritRepository(db);
var gabarits = gabaritrepository.Get(g => g.Designation == designation)
//Map your Gabarit to your ViewModel here
.Select(x => new GabaritViewModel {
CodeBarre = x.CodeBarre,
Etat = x.Etat
}).ToList();
return View(gabarits);
}
Very new to ASP.NET MVC and Entity Framework.
I'm trying to set up a database with three tables, when I run my code and go to the page "Tickets", I get the following exception:
There is already an open DataReader associated with this Command which must be closed first.
Class 1
public class Ticket
{
[Key]
public int ID { get; set; }
public string Description { get; set; }
[ForeignKey("Practice")]
public int PracticeID { get; set; }
public string Contact { get; set; }
public string Category { get; set; }
//insert Support type using ViewBag (Support type listed in Models.Practices)
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Due { get; set; }
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime TimeLogged { get; set; }
[ForeignKey("Consultant")]
public int ConsultantID { get; set; }
public string ConsultantName { get; set; }
public string Status { get; set; }
public virtual Practice Practice { get; set; }
public virtual Consultant Consultant { get; set; }
}
Class 2:
public class Practice
{
[Key]
public int PracticeID { get; set; }
[Display(Name = "Practice Name")]
public string PracName { get; set; }
[Display(Name = "Practice Number")]
public int PracNumber { get; set; }
public string Contact { get; set; }
[Display(Name = "Support Type")]
public string Support { get; set; }
public string Tel { get; set; }
public string Cell { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public string Address { get; set; }
public virtual List<Ticket> Ticket { get; set; }
}
Class 3:
public class Consultant
{
[Key]
public int ConsultantID { get; set; }
public string Name { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
public string Role { get; set; }
public virtual List<Ticket> Ticket { get; set; }
}
I have a search function in my TicketsController:
public ActionResult Index(string searchString, string Consultants)
{
var UserLst = new List<string>();
var UserQry = from d in db.Consultants
orderby d.Name
select d.Name;
UserLst.AddRange(UserQry.Distinct());
ViewBag.User = new SelectList(UserLst);
var tickets = from m in db.Ticket
select m;
if (!String.IsNullOrEmpty(searchString))
{
tickets = tickets.Where(s => s.Description.Contains(searchString));
}
if (!string.IsNullOrEmpty(Consultants))
{
tickets = tickets.Where(x => x.ConsultantName == Consultants);
}
return View(tickets);
}
The error seems to be coming from the HTML code in the INDEX.
#model IEnumerable<MAD.Models.Ticket>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<p>
User: #Html.DropDownList("User", "All")
Description: #Html.TextBox("SearchString") <br />
<input type="submit" value="Search" />
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Consultant.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Practice.PracName)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Contact)
</th>
<th>
#Html.DisplayNameFor(model => model.Category)
</th>
<th>
#Html.DisplayNameFor(model => model.Due)
</th>
<th>
#Html.DisplayNameFor(model => model.TimeLogged)
</th>
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Consultant.Name)--ERROR CODE
</td>
<td>
#Html.DisplayFor(modelItem => item.Practice.PracName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Contact)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category)
</td>
<td>
#Html.DisplayFor(modelItem => item.Due)
</td>
<td>
#Html.DisplayFor(modelItem => item.TimeLogged)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</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 })
</td>
</tr>
}
</table>
You have passed in an IQueryable from your controller as your model - called tickets in the controller method. When you start your for each loop on the model, EF starts retrieving results through the connection, but it doesn't actually finish using the connection for this until the end of the loop. The line which is causing the error is trying to access the related Consultant property, which triggers EF to try to load that from the DB, but that causes an exception because you are still in the loop and it is still using the connection to retrieve the tickets query.
The easiest way around this is to force EF to retrieve the results before the loop. I would go for changing the final line in the controller to View (tickets.ToArray) or similar.
I'm not sure, but enabling multiple active result sets might also fix this.
I have spent the past day and a half trying to find this answer and sometimes it seems like I am so close but so far no luck.
I have a controller where I defined a LINQ query and am trying to figure out how to pass the results onto a listing view. the following is the Controller code:
namespace CMS.Controllers
{
public class SurveyController : Controller
{
private SupportEntities supdb = new SupportEntities();
private BuisnessEntities bsdb = new BuisnessEntities();
//
// GET: /Survey/BizSurveyC
public ViewResult BizSurveyC(string nipaKey, string bOrg)
{
// use the next two lines for testing and then either delete or comment them out.
nipaKey = "22";
bOrg = "MPC";
var Cquery = from Mstr in bsdb.BizOrgInsts
join Dat in bsdb.BizSurveyQ on Mstr.ID equals Dat.MASTERID
where Mstr.NIPAKEY == nipaKey & Mstr.FULCIRCORG == bOrg
orderby Mstr.STREETSUFX, Dat.ADDRESS, Mstr.NUMBER
select new { MasterId = Mstr.ID, Name = Mstr.OLDNAME, Mstr.ADDRESS, Mstr.NIPAKEY, Dat.SURVEYDATE, SurveyId = Dat.ID, Dat.RESURVEYOF, Dat.STAMP };
//ViewBag.BizQuery = Cquery;
ViewData["BizQuery"] = new SelectList(Cquery);
return View();
}
}
}
As you can tell by looking I have tried ViewData and Viewbag but so far with no luck
Here are the way things are now appearing:
ViewModel Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CMS.Models
{
public class BizSurveyCVM
{
public long? MasterId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string NipaKey { get; set; }
public string Date { get; set; }
public long? SurveyId { get; set; }
public long? Resurvey { get; set; }
public string DateStamp { get; set; }
}
}
Modified Action
var Cquery = (from Mstr in bsdb.BizOrgInsts
join Dat in bsdb.BizSurveyQ on Mstr.ID equals Dat.MASTERID
where Mstr.NIPAKEY == nipaKey & Mstr.FULCIRCORG == bOrg
orderby Mstr.STREETSUFX, Dat.ADDRESS, Mstr.NUMBER
select new BizSurveyCVM
{
MasterId = Mstr.ID,
Name = Mstr.OLDNAME,
Address = Mstr.ADDRESS,
NipaKey = Mstr.NIPAKEY,
Date = Dat.SURVEYDATE,
SurveyId = Dat.ID,
Resurvey = Dat.RESURVEYOF,
DateStamp = Dat.STAMP
}).ToList();
return View(Cquery);
}
BizSurveyC View
#model List<CMS.Models.BizSurveyCVM>
<table>
<tr>
<th>
MasterId
</th>
<th>
Name
</th>
<th>
Address
</th>
<th>
NipaKey
</th>
<th>
Date
</th>
<th>
SurveyId
</th>
<th>
Resurvey
</th>
<th>
DateStamp
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.MasterId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.NipaKey)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.SurveyId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Resurvey)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateStamp)
</td>
</table>
here is the resulting view:
SORRY NOT ALLOWED TO SAVE IMAGE YET BUT IN THE VIEW I HAVE HEADERS BUT NO DATA.
I obviously have some work to do in the view or maybe the query but things are looking much better thanks so everyone's help. Thank you very much
You could create a ViewModel class to hold whatever your query results are and then strongly type your view for the new ViewModel class:
ViewModel Class:
public class BizSurveyCVM
{
public long MasterId { get; set; }
public string Name { get; set; }
...
}
Modified Action:
var Cquery = (from Mstr in bsdb.BizOrgInsts
join Dat in bsdb.BizSurveyQ on Mstr.ID equals Dat.MASTERID
where Mstr.NIPAKEY == nipaKey & Mstr.FULCIRCORG == bOrg
orderby Mstr.STREETSUFX, Dat.ADDRESS, Mstr.NUMBER
select new BizSurveyCVM { MasterId = Mstr.ID, Name = Mstr.OLDNAME, ...}
).ToList();
return View(Cquery);
BizSurveyC View
#model List<{namespace}.BizSurveyCVM>
#foreach(var item in Model) {
{HTML Mark-up}
}
EDIT: Here's an updated example of the view based on the updated question:
#model List<{namespace}.BizSurveyCVM>
#foreach(var item in Model) {
<tr>
<td>
#item.MasterId
</td>
<td>
#item.Name
</td>
<td>
#item.Address
</td>
...
</tr>
}
return View(Cquery);
or
return View("ViewName",Cquery);
and then in your view, the model type should match the type of Cquery. But I find that its easier (assuming you're using VS) to just right click in the method body somewhere and click "add view", and select the model from the list of model types.
Are you sure that you want do?
it's more useful the collection in the view, so you can build anything you need, like a select list.
don't forget define who is your datavalue and displayvalue in the select list, like..
ViewData["BizQuery"] = new SelectList(Cquery, null, "MasterId", "Name");
Ok, your code works for me, so check your view, you must do the correct cast of your object in the viewdata
you need have something like this
#foreach (SelectListItem item in (SelectList)ViewData["BizQuery"])
{
<p>#item.Text</p>
}