Print Table with List Variable From Entities in MVC - c#

I've not worked MVC for a long time; I'm a fresh guy to this. So, I have these two entities:
// Entity Worker
[Display(Name = "ID")]
public Int32 Id { get; set; }
[Display(Name = "Número")]
public Int32 Numero { get; set; }
[Display(Name = "Nome")]
// Entity Lottery
public Int32 Id { get; set; }
[Display(Name = "Tipo")]
public String Tipo { get; set; }
[Display(Name = "Data")]
public DateTime Data { get; set; }
[Display(Name = "Observações")]
public List<Worker> FuncionariosSorteados { get; set; }
So, for each lottery entity, I will have a List of workers. I am passing the values to the View by the controller, like this:
public ActionResult Details(int id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Lottery lottery = service.FindLottery(id);
if (sorteio == null)
{
return HttpNotFound();
}
return View(lottery);
}
Where the service is my Repository for the connection to database (in this case he do a search by ID on database to get the right lottery.
Here my doubt begin, if I want to do a table for the lotteries, I can do it doing (using Lottery model)
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Tipo)
</td>
<td>
#Html.DisplayFor(modelItem => item.Data)
</td>
<td>
#Html.DisplayFor(modelItem => item.Observacoes)
</tr>
}
But how I can do the same for the public List<Worker> FuncionariosSorteados? I just want to print the public List<Worker> FuncionariosSorteados in a GridMvc table, but through the model I cant have access to it!

I believe you need to iterate through the list within the foreach loop you already created. Something like this:
#foreach (var item in Model)
{
<table>
<tr>
<td>
#Html.DisplayFor(modelItem => item.Tipo)
</td>
<td>
#Html.DisplayFor(modelItem => item.Data)
</td>
<td>
#Html.DisplayFor(modelItem => item.Observacoes)
</td>
</tr>
</table>
<table>
#foreach(var w in Model.FuncionariosSorteados )
{
<tr>
<td>#Html.DisplayFor(w => w.Id)</td>
<td>#Html.DisplayFor(w => w.Numero)</td>
</tr>
}
</table>
}

I'm confused because in your action, you're pulling a single lottery record and passing that to your view, but in your view, you're iterating through what appears to be an IEnumerable<Lottery>.
Since you'd have no issues accessing FuncionariosSorteados off of a Model of type Lottery, I'm assuming the view is actually using IEnumerable<Lottery>. For an enumerable, you have to iterate over the list and access the properties on the individual items. For example:
#model IEnumerable<Lottery>
#Model.FuncionariosSorteados <!-- fail -->
#foreach (var lottery in Model)
{
#lottery.FuncionariosSorteados <!-- success -->
}

For your second entity you could create it like this:
Entitie Lottery
public Lottery( )
{
FuncionariosSorteados = new List <Worker>();
}
public Int32 Id { get; set; }
[Display(Name = "Tipo")]
public String Tipo { get; set; }
[Display(Name = "Data")]
public DateTime Data { get; set; }
[Display(Name = "Observações")]
public virtual List<Worker> FuncionariosSorteados { get; set; }
And thenin your view you can use a foreach loup to iterate inside the lists

Related

foreach statement cannot operate because does not contain a public definition for 'GetEnumerator' with Tuples ASP.NET MVC

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.

How to pass AnonymousType to asp.net MVC 5 view?

I am trying to pass anonymous type to view but It's get Error to find The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType1`2[System.Int32,System.Int32]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Test.Models.BidsDetails]'.
Where my model
public class BidsDetails
{
public int Id { get; set; }
public int BidsId { get; set; }
public int ProductId { get; set; }
public int BidsPrice { get; set; }
public virtual Bids Bids { get; set; }
public virtual Product Product { get; set; }
}
my Controller
[HttpGet]
public ActionResult Winner()
{
TestDbContext db = new TestDbContext();
var result = db.bidsDetails
.GroupBy(g => g.ProductId)
.Select(s => new
{
productId = s.Key,
BidsPrice = s.Max(m => m.BidsPrice)
}).ToList();
return View(result);
}
My view
#model IEnumerable<Test.Models.BidsDetails>
#{
ViewBag.Title = "Winner";
}
<h2>Winner</h2>
<table class="table">
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Bids.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Product.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => item.BidsPrice)
</td>
</tr>
}
</table>
I am beginner to asp.net MVC .
So, How to solve this problem ?

I Can't Pass IEnumerable ViewModel in my View in asp.net mvc [duplicate]

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);
}

Trouble passing data from database table to view

I am filling an SQL table with a query and then trying to pass the data from the model (for the table) into the view. I am attempting to use a ViewModel to pass the data to the view in a Controller Action.
Here is the Model:
public partial class Report
{
public int Id { get; set; }
public string Number { get; set; }
public Nullable<decimal> Amount { get; set; }
public Nullable<System.DateTime> Date { get; set; }
public Nullable<int> ReasonId { get; set; }
public string Notes { get; set; }
}
IEnumerable ViewModel:
public class ReportViewModel
{
public IEnumerable<Report> Reports { get; set; }
}
Controller Action:
[HttpPost]
public ActionResult UploadValidationTable(HttpPostedFileBase csvFile)
{
//Unrelated Code to read a CSV into another database table goes here
//But was removed so it wouldn't be confusing.
var db = new Report();
var reportModel = new ReportViewModel()
{
Reports = new List<Report>() {new Report()}
};
return View("Upload", reportModel);
}
View:
#model Entities.Models.ReportViewModel
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Number</th>
<th>Amount</th>
<th>Date</th>
<th>Reason Id</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var item in Model.Reports.Where(x => x.Id != null))
{
<tr>
<td>
#item.Id
</td>
<td>
#item.Number
</td>
<td>
#item.Amount
</td>
<td>
#item.Date
</td>
<td>
#item.ReasonId
</td>
<td>
#item.Notes
</td>
</tr>
}
}
</tbody>
</table>
But I get an exception when I try to return the View which says ReportViewModel is not assignable to model type IEnumerable ReportViewModel
So I am just trying to pass all the rows from the Report database to an HTML table in my view. Any help, or a better way to do this would be appreciated.

Foreach statement cannot operate on variables of type [Tracker.Models.INV_Assets]?

I'm putting together a fairly simple Code-First MVC5 Inventory Tracking application. I've gotten my app to Seed() and all of my Maintenance tables (Locations, Vendors, Statuses, etc.) I can view/create/edit/delete. I'm now working on the View for my main [INV_Assets] model, but when trying to foreach through the items in my model to display all [INV_Assets] in a table, I get the error: foreach statement cannot operate on variables of type 'Tracker.Models.INV_Assets' because 'Tracker.Models.INV_Assets' does not contain a public definition for 'GetEnumerator'.
Below is the Model for my [INV_Assets]:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using GridMvc.DataAnnotations;
using System.Web.Mvc;
using Tracker.Models;
namespace Tracker.Models
{
[GridTable(PagingEnabled = true, PageSize = 30)]
public class INV_Assets
{
// Setting GridColumn Annotations allows you to use AutoGenerateColumns on view to auto create the Grid based on the model.
public int Id { get; set; }
public int Model_Id { get; set; }
[ForeignKey("Model_Id")]
public virtual INV_Models Model { get; set; }
[Required]
public int Manufacturer_Id { get; set; }
[ForeignKey("Manufacturer_Id")]
public virtual INV_Manufacturers Manufacturer { get; set; }
[Required]
public int Type_Id { get; set; }
[ForeignKey("Type_Id")]
public virtual INV_Types Type { get; set; }
[Required]
public int Location_Id { get; set; }
[ForeignKey("Location_Id")]
public virtual INV_Locations Location { get; set; }
public int Vendor_Id { get; set; }
[ForeignKey("Vendor_Id")]
public virtual INV_Vendors Vendor { get; set; }
[Required]
public int Status_Id { get; set; }
[ForeignKey("Status_Id")]
public virtual INV_Statuses Status { get; set; }
public string ip_address { get; set; }
public string mac_address { get; set; }
public string note { get; set; }
public string owner { get; set; }
public decimal cost { get; set; }
public string po_number { get; set; }
public string description { get; set; }
public int invoice_number{ get; set; }
[Required]
public string serial_number { get; set; }
[Required]
public string asset_tag_number { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? acquired_date { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? disposed_date { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime created_date { get; set; }
[Required]
public string created_by { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime modified_date { get; set; }
public string modified_by { get; set; }
// Flag to specify if item is available? (Not signed out, not auctioned, recycled, etc.)
//public bool available { get; set; }
}
}
[INV_Assets] View:
#using GridMvc.Html
#model Tracker.Models.INV_Assets
#{
ViewBag.Title = "Home Page";
}
<table style="width:100%;">
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.Status)</td>
<td>#Html.DisplayFor(modelItem => item.Location)</td>
<td>#Html.DisplayFor(modelItem => item.owner)</td>
<td>#Html.DisplayFor(modelItem => item.Type)</td>
<td>#Html.DisplayFor(modelItem => item.Manufacturer)</td>
<td>#Html.DisplayFor(modelItem => item.Model)</td>
<td>#Html.DisplayFor(modelItem => item.Vendor)</td>
<td>#Html.DisplayFor(modelItem => item.description)</td>
<td>#Html.DisplayFor(modelItem => item.asset_tag_number)</td>
<td>#Html.DisplayFor(modelItem => item.serial_number)</td>
<td>#Html.DisplayFor(modelItem => item.ip_address)</td>
<td>#Html.DisplayFor(modelItem => item.mac_address)</td>
<td>#Html.DisplayFor(modelItem => item.po_number)</td>
<td>#Html.DisplayFor(modelItem => item.invoice_number)</td>
<td>#Html.DisplayFor(modelItem => item.cost)</td>
<td>#Html.DisplayFor(modelItem => item.note)</td>
<td>#Html.DisplayFor(modelItem => item.acquired_date)</td>
<td>#Html.DisplayFor(modelItem => item.disposed_date)</td>
<td>#Html.DisplayFor(modelItem => item.created_date)</td>
<td>#Html.DisplayFor(modelItem => item.created_by)</td>
<td>#Html.DisplayFor(modelItem => item.modified_date)</td>
<td>#Html.DisplayFor(modelItem => item.modified_by)</td>
</tr>
}
</table>
I'm not quite sure how to get around this error and wondered if someone with more experience could weigh-in?
I am getting no issue (not sure why) from my [INV_Locations] Model/View when doing the same:
[INV_Locations]:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Tracker.Models
{
public class INV_Locations
{
public int Id { get; set; }
public string location_dept { get; set; }
public string location_room { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime created_date { get; set; }
[Required]
public string created_by { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime modified_date { get; set; }
public string modified_by { get; set; }
}
}
[INV_Locations] View:
#model IEnumerable<Tracker.Models.INV_Locations>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Maintenance - Locations</h3>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th></th>
<th>
#*#Html.DisplayNameFor(model => model.location_dept)*#
Dept:
</th>
<th>
Room:
</th>
<th>
Created:
</th>
<th>
By:
</th>
<th>
Modified:
</th>
<th>
By:
</th>
</tr>
#foreach (var item in Model) {
<tr>
<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>
<td>
#Html.DisplayFor(modelItem => item.location_dept)
</td>
<td>
#Html.DisplayFor(modelItem => item.location_room)
</td>
<td>
#Html.DisplayFor(modelItem => item.created_date)
</td>
<td>
#Html.DisplayFor(modelItem => item.created_by)
</td>
<td>
#Html.DisplayFor(modelItem => item.modified_date)
</td>
<td>
#Html.DisplayFor(modelItem => item.modified_by)
</td>
</tr>
}
</table>
I tried changing #model Tracker.Models.INV_Assets to #model IEnumerable<Tracker.Models.INV_Assets> on my [INV_Assets] View (just like how my [INV_Locations] View has it. This allows my solution to Build, but when trying to run my application to that View I receive:
System.InvalidOperationException
The model item passed into the dictionary is of type 'Tracker.Models.INV_Assets', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1[Tracker.Models.INV_Assets]'.
EDIT - Regarding Shyju's Suggestion:
I changed my HomeController Index() from:
TrackerContext _db = new TrackerContext();
public ActionResult Index(INV_Assets defModel)
{
return View(defModel);
}
to:
TrackerContext _db = new TrackerContext();
public ActionResult Index(INV_Assets defModel)
{
var assetList = new List<Tracker.Models.INV_Assets>();
assetList.Add(defModel);
return View(assetList);
}
While my View now loads, all I get for the Table HTML is:
<table style="width:100%;">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>0</td>
<td>0.00</td>
<td></td>
<td></td>
<td></td>
<td>01/01/0001</td>
<td></td>
<td>01/01/0001</td>
<td></td>
</tr>
</table>
I've confirmed that my DBContext has 2 complete [INV_Assets] records in it, but they are not showing up in the View? How do I correctly load all the instances of my [INV_Assets] model into the new assetList variable?
EDIT2:
Modified my Index() to:
TrackerContext _db = new TrackerContext();
public ActionResult Index(INV_Assets defModel)
{
var assetList = _db.INV_Assets.ToList(); // EXCEPTION
return View(assetList);
}
but now, while the solution builds, the application fails when I try to run it. Details below:
Error: An exception of type 'System.Data.DataException' occurred in EntityFramework.dll but was not handled in user code. Additional information: An exception occurred while initializing the database. See the InnerException for details.
Message: An exception occurred while initializing the database. See the InnerException for details.
InnerException: {"The underlying provider failed on Open."}
Source: EntityFramework
Your view is bound to a single instance of Tracker.Models.INV_Assets. But inside your view, you are trying to loop through it. You need to make sure what was passed to your view is a collection, so that we can loop through it.
In INV Assets view, change
#model Tracker.Models.INV_Assets
to
#model List<Tracker.Models.INV_Assets>
Also you need to make sure that you are passing a collection of INV_Assets objects from your action method.
public ActionResult INVAssets()
{
var assetList=new List<Tracker.Models.INV_Assets>();
// Ex : manually adding one record. replace with your actual code to load data
// to do : Add item to the list now
assetList.Add(new INV_Assets { Name ="Test"});
return View(assetList);
}
Edit : As per the edit in the question
Your Index action should not be taking an object of INV_Assets as parameter.
TrackerContext _db = new TrackerContext();
public ActionResult Index()
{
var assetList =_db.INV_Assets.ToList();
return View(assetList);
}
Asssuming INV_Assets is a property on your TrackerContext class. If your property name is different, change the above code to reflect that.
If you want to load load the assets for a specific location, update your Index action method to accept the location id as a parameter.
public ActionResult Index(int id)
{
var assetList =_db.INV_Assets.Where(s=>s.Location_Id==id).ToList();
return View(assetList);
}
So your url to access this page would be like
http://yoursitename/YourControllerName/Index/5
where 5 is a valid location id which has some assets associated with it.

Categories

Resources