How Do I Use A Tuple Properly in ASP.NET MVC 4 - c#

I'm trying to use two models in one view using a tuple but I'm getting this error:
Server Error in '/' Application.
The model item passed into the dictionary is of type 'PagedList.PagedList1[S00117372CA3.Product]', but this dictionary requires a model item of type 'System.Tuple2[PagedList.IPagedList1[S00117372CA3.Product],System.Collections.Generic.IEnumerable1[S00117372CA3.Order]]'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'PagedList.PagedList1[S00117372CA3.Product]', but this dictionary requires a model item of type 'System.Tuple2[PagedList.IPagedList1[S00117372CA3.Product],System.Collections.Generic.IEnumerable1[S00117372CA3.Order]]'.
Here is my code:
#*#model PagedList.IPagedList<S00117372CA3.Product>*#
#model Tuple<PagedList.IPagedList<S00117372CA3.Product>, IEnumerable<S00117372CA3.Order>>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Item1[0].ProductName)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1[0].Supplier.CompanyName)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1[0].Category.CategoryName)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1[0].QuantityPerUnit)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1[0].UnitPrice)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1[0].UnitsInStock)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1[0].UnitsOnOrder)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1[0].ReorderLevel)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1[0].Discontinued)
</th>
<th></th>
</tr>
#foreach (var item in Model.Item1) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.CompanyName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category.CategoryName)
</td>
<td>
#Html.DisplayFor(modelItem => item.QuantityPerUnit)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitsInStock)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitsOnOrder)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReorderLevel)
</td>
<td>
#Html.DisplayFor(modelItem => item.Discontinued)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) |
#Html.ActionLink("Details", "Details", new { id=item.ProductID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ProductID })
</td>
</tr>
}
</table>
<div>
Page #(Model.Item1.PageCount < Model.Item1.PageNumber ? 0 : Model.Item1.PageNumber) of #Model.Item1.PageCount
#if (Model.Item1.HasPreviousPage)
{
#Html.ActionLink("<<", "Index", new { page = 1})
#Html.Raw(" ");
#Html.ActionLink("< Prev", "Index", new {page = Model.Item1.PageNumber - 1})
}
else{
#:<<
#Html.Raw(" ");
#:< Prev
}
#if (Model.Item1.HasNextPage)
{
#Html.ActionLink("Next >", "Index", new {page = Model.Item1.PageNumber + 1})
#Html.Raw(" ");
#Html.ActionLink(">>", "Index", new {page = Model.Item1.PageCount})
}
else{
#:Next >
#Html.Raw(" ")
#:>>
}
</div>
#foreach (var item in Model.Item2)
{
#Html.Partial("_Orders")
}
Here is my controller code as requested:
var q = (from o in db.Order_Details
where o.ProductID == id
join ord in db.Orders
on o.OrderID equals ord.OrderID
orderby o.Quantity descending
select ord);
var qm = q.Take(3);
return PartialView("_Orders", qm.ToList());

Essentially, you're just trying to pass multiple models to your view. As you can only pass one type to a view, the way to do what you want is to wrap your models in a view model and pass that to your view instead. Something like:
public class ProductViewModel
{
public IPagedList<Product> Products { get; set; }
public IEnumerable<Order> Orders { get; set; }
}
public ActionResult Index()
{
var model = new ProductViewModel();
model.Products = // ... fetch from database
model.Orders = // ... fetch from database
return View(model);
}
The view can now be strongly-typed to the view model:
#model ProductViewModel

Related

View in ASP.NET Core 5 MVC display as required

I am creating an ASP.NET Core 5 MVC web app and I have a problem.
View only display the same value.
I have debug and the controller seem to be ok.
But I don't have any idea why the view is only display 9 row and all rows are the same.
Here is the code in the controller:
public class MatchesController : Controller
{
private ISender _mediator;
public MatchesController(ISender mediator)
{
_mediator = mediator;
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> ViewAllMatch()
{
var matchQuery = await _mediator.Send(new GetMatchesDetail());
// ReUse model from Apllication Layer
// Manual Mapping from matches to MatchViewModel
// GetMatchesDetail : IRequest<IEnumerable<MatchesDetail>>
// Manual Mapping IEnumerable<MatchesDetail> =>IEnumerable<MatchViewModel>
MatchViewModel matchesvm = new MatchViewModel();
List<MatchViewModel> retList = new List<MatchViewModel>();
// IEnumerable<MatchesDetail> retList;
foreach (var item in matchQuery)
{
matchesvm.MatchId = item.MatchId;
matchesvm.MatchNumber = item.MatchNumber;
matchesvm.DateMatch = item.DateMatch;
matchesvm.TimeMatch = item.TimeMatch;
matchesvm.MatchYear = item.MatchYear;
matchesvm.SeasonId = item.SeasonId;
matchesvm.SeasonName = item.SeasonName;
matchesvm.Round = item.Round;
matchesvm.Stage = item.Stage;
matchesvm.SubStage = item.SubStage;
matchesvm.HTeam = item.HTeam;
matchesvm.HGoal = item.HGoal;
matchesvm.HTeamCode = item.HTeamCode;
matchesvm.GGoal = item.GGoal;
matchesvm.GTeam = item.GTeam;
matchesvm.GTeamCode = item.GTeamCode;
matchesvm.WinNote = item.WinNote;
matchesvm.Stadium = item.Stadium;
matchesvm.Referee = item.Referee;
matchesvm.Visistors = item.Visistors;
retList.Add(matchesvm);
}
return View(retList);
}
}
And here is the view:
#model IEnumerable<MatchViewModel>
#{
ViewData["Title"] = "ViewAllMatch";
string flag1, flag2;
}
<h1>ViewAllMatch</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.MatchId)
</th>
<th>
#Html.DisplayNameFor(model => model.MatchNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.DateMatch)
</th>
<th>
#Html.DisplayNameFor(model => model.TimeMatch)
</th>
<th>
#Html.DisplayNameFor(model => model.MatchYear)
</th>
<th>
#Html.DisplayNameFor(model => model.SeasonId)
</th>
<th>
#Html.DisplayNameFor(model => model.SeasonName)
</th>
<th>
#Html.DisplayNameFor(model => model.Round)
</th>
<th>
#Html.DisplayNameFor(model => model.Stage)
</th>
<th>
#Html.DisplayNameFor(model => model.SubStage)
</th>
<th>
#Html.DisplayNameFor(model => model.HTeam)
</th>
<th>
#Html.DisplayNameFor(model => model.HTeamCode)
</th>
<th>
#Html.DisplayNameFor(model => model.HGoal)
</th>
<th>
#Html.DisplayNameFor(model => model.GGoal)
</th>
<th>
#Html.DisplayNameFor(model => model.GTeam)
</th>
<th>
#Html.DisplayNameFor(model => model.GTeamCode)
</th>
<th>
#Html.DisplayNameFor(model => model.WinNote)
</th>
<th>
#Html.DisplayNameFor(model => model.Stadium)
</th>
<th>
#Html.DisplayNameFor(model => model.Referee)
</th>
<th>
#Html.DisplayNameFor(model => model.Visistors)
</th>
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.MatchId)
</td>
<td>
#Html.DisplayFor(modelItem => item.MatchNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateMatch)
</td>
<td>
#Html.DisplayFor(modelItem => item.TimeMatch)
</td>
<td>
#Html.DisplayFor(modelItem => item.MatchYear)
</td>
<td>
#Html.DisplayFor(modelItem => item.SeasonId)
</td>
<td>
#Html.DisplayFor(modelItem => item.SeasonName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Round)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stage)
</td>
<td>
#Html.DisplayFor(modelItem => item.SubStage)
</td>
<td class="text-center">
#Html.DisplayFor(modelItem => item.HTeam)
</td>
<td>
#{
flag1 = "/img/Team/"+#item.HTeamCode+".png";
flag2= "/img/Team/" + #item.GTeamCode + ".png";
}
<img src="#flag1" />
#*#Html.DisplayFor(modelItem => item.HTeamCode)*#
</td>
<td>
#Html.DisplayFor(modelItem => item.HGoal)
</td>
<td>
#Html.DisplayFor(modelItem => item.GGoal)
</td>
<td>
#Html.DisplayFor(modelItem => item.GTeam)
</td>
<td>
#Html.DisplayFor(modelItem => item.GTeamCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.WinNote)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stadium)
</td>
<td>
#Html.DisplayFor(modelItem => item.Referee)
</td>
<td>
#Html.DisplayFor(modelItem => item.Visistors)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
The reason why you always get the same value is your MatchViewModel is new outside the foreach method. This means you always added the same MatchViewModel and its value has been changed during each foreach. This will make the List view model always added the same viewmodel like your view shows always the same row.
I suggest you could try below codes:
public async Task<IActionResult> ViewAllMatch()
{
var matchQuery = await _mediator.Send(new GetMatchesDetail());
//ReUse model from Apllication Layer
//Manual Mapping from matches to MatchViewModel
//GetMatchesDetail : IRequest<IEnumerable<MatchesDetail>>
//Manual Mapping IEnumerable<MatchesDetail> =>IEnumerable<MatchViewModel>
List<MatchViewModel> retList = new List<MatchViewModel>();
//IEnumerable<MatchesDetail> retList;
foreach (var item in matchQuery)
{
MatchViewModel matchesvm = new MatchViewModel();
#region ManualMapping
matchesvm.MatchId = item.MatchId;
matchesvm.MatchNumber = item.MatchNumber;
matchesvm.DateMatch = item.DateMatch;
matchesvm.TimeMatch = item.TimeMatch;
matchesvm.MatchYear = item.MatchYear;
matchesvm.SeasonId = item.SeasonId;
matchesvm.SeasonName = item.SeasonName;
matchesvm.Round = item.Round;
matchesvm.Stage = item.Stage;
matchesvm.SubStage = item.SubStage;
matchesvm.HTeam = item.HTeam;
matchesvm.HGoal = item.HGoal;
matchesvm.HTeamCode = item.HTeamCode;
matchesvm.GGoal = item.GGoal;
matchesvm.GTeam = item.GTeam;
matchesvm.GTeamCode = item.GTeamCode;
matchesvm.WinNote = item.WinNote;
matchesvm.Stadium = item.Stadium;
matchesvm.Referee = item.Referee;
matchesvm.Visistors = item.Visistors;
#endregion
retList.Add(matchesvm);
}
return View(retList);
//return View(matches); //IEnumerable<MatchesDetail>
}
You have bug in your code, you should create a new MatchViewModel instance for each item inside of the loop
foreach (var item in matchQuery)
{
var matchesvm = new MatchViewModel();
matchesvm.MatchId = item.MatchId;
... and so on
}
but you can use Linq instead foreach loop
var retList= matchQuery.Select(item=> new MatchViewModel
{
MatchId = item.MatchId;
MatchNumber = item.MatchNumber;
DateMatch = item.DateMatch
.... and so on
}).ToList();
return View(retList);
IMHO no much sense to convert IEnumerable of MatchesDetail => IEnumerable of MatchViewModel since they have the same property names and you use them only to display data. You can use matchQuery directly
return View(matchQuery);
and view
#model IEnumerable<MatchesDetail>

Error when trying to create PDF with Rotativa

My goal is to allow users to print to pdf, a view. I found a Nuget called Rotativa and followed some very basic tutorials. In test, it worked perfectly and looked like a great answer to meet my needs.
However, I am finding that implementing it into the actual working project, is giving me errors that the simple test did not.
I have an index view that is a list. I want users to print this list to pdf. I have tried many different classes of Rotativa (ViewAsPDF, ActionAsPDF, GeneratePDF. . . ). I have researched and read numerous tutorials . .but I think the problem is more related to my Model. .
Here is what I have so far
Index View
#model IEnumerable<ICS20web.Models.IndexViewModel>
#{
ViewBag.Title = "Index";
}
<style>
#content {
}
.even {
background-color: #dcf1b8;
}
.odd {
background-color: #f4ffe1;
}
</style>
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<p>
<p>
#Html.ActionLink("Print", "PrintAllReport")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ItemDescription)
</th>
<th>
#Html.DisplayNameFor(model => model.OriginalDate)
</th>
<th>
#Html.DisplayNameFor(model => model.TransType)
</th>
<th>
#Html.DisplayNameFor(model => model.LastUpdatedBy)
</th>
<th>
#Html.DisplayNameFor(model => model.ContactName)
</th>
<th>
#Html.DisplayNameFor(model => model.OpenClosed)
</th>
<th>
#Html.DisplayNameFor(model => model.CurrentStatus)
</th>
<th>
#Html.DisplayNameFor(model => model.CurrentStatusDate)
</th>
<th>
#Html.DisplayNameFor(model => model.RequsitionNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.PONumber)
</th>
<th>
#Html.DisplayNameFor(model => model.DeliveryMonth)
</th>
<th>
#Html.DisplayNameFor(model => model.DeliveryYear)
</th>
<th>
#Html.DisplayNameFor(model => model.UnitsOrdered)
</th>
<th>
#Html.DisplayNameFor(model => model.Emergency)
</th>
<th>
#Html.DisplayNameFor(model => model.Comments)
</th>
<th>
#Html.DisplayNameFor(model => model.DeliveryUnit)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ItemDescription)
</td>
<td>
#Html.DisplayFor(modelItem => item.OriginalDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.TransType)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastUpdatedBy)
</td>
<td>
#Html.DisplayFor(modelItem => item.ContactName)
</td>
<td>
#Html.DisplayFor(modelItem => item.OpenClosed)
</td>
<td>
#Html.DisplayFor(modelItem => item.CurrentStatus)
</td>
<td>
#Html.DisplayFor(modelItem => item.CurrentStatusDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.RequsitionNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.PONumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.DeliveryMonth)
</td>
<td>
#Html.DisplayFor(modelItem => item.DeliveryYear)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitsOrdered)
</td>
<td>
#Html.DisplayFor(modelItem => item.Emergency)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comments)
</td>
<td>
#Html.DisplayFor(modelItem => item.DeliveryUnit)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.TransID })
</td>
</tr>
}
</table>
The View loads in the browser, with correct data from the model, properly. But, when the user clicks the ActionLink PrintAllReport . . . I see the following error: System.NullReferenceException: Object reference not set to an instance of an object.
Referencing line #foreach (var item in Model)
I believe that is telling me that the Model is empty? But, how can that be, when it populates in the browser just fine.
Here is My Index Controller Action
public ActionResult Index()
{
var q = from tr in db.ICS_Transactions
join un in db.ICS_Units
on tr.DeliveryUnitID equals un.DeliveryUnitID
join kt in db.ICS_Contacts
on tr.Contact equals kt.LoginID
join sp in db.ICS_Supplies on tr.SuppliesID equals sp.Supplies_ID
orderby tr.Emergency descending, tr.TransID ascending
select new IndexViewModel
{
TransID = tr.TransID,
ItemDescription = sp.ItemDescription,
OriginalDate = tr.OriginalDate,
TransType = tr.TransType,
LastUpdatedBy = tr.LastUpdatedBy,
ContactName = kt.ContactName,
OpenClosed = tr.OpenClosed,
CurrentStatus = tr.CurrentStatus,
CurrentStatusDate = tr.CurrentStatusDate,
RequsitionNumber = tr.RequsitionNumber,
PONumber = tr.PONumber,
DeliveryMonth = tr.DeliveryMonth,
DeliveryYear = tr.DeliveryYear,
UnitsOrdered = tr.UnitsOrdered,
Emergency = tr.Emergency,
Comments = tr.Comments,
DeliveryUnit = un.DeliveryUnit,
PhoneNumber = un.PhoneNumber,
Street = un.Street,
City = un.City,
State = un.State,
ZipCode = un.ZipCode,
Building = un.Building,
Room = un.Room
}
;
return View(q.Where(d => d.OpenClosed == "Open").ToList());
}
And here is my PrintAllReport Action
public ActionResult PrintAllReport()
{
var model = new IndexViewModel();
//Code to get content
return new Rotativa.ViewAsPdf("Index") { FileName = "TestViewAsPdf.pdf" };
}
This generates the Object Reference Error. I am confused. Shouldn't this work exactly as the index loaded in the browser? What am I missing?
I have also tried it this way:
public ActionResult PrintAllReport()
{
var report = new ActionAsPdf("Index");
return report;
}
The latter gives me an authentication error: You are not authorized to view this page due to invalid authentication headers.
I am new to MVC5 and I am confused as to why the index page loads properly, but the action PrintAllReport is failing to open in pdf. And what I need to change to make it work properly.
Update:
After Stuard gave me some good information, I have made some changes, as follows
{
var viewModel = new IndexViewModel();
var report = new ViewAsPdf("Index", viewModel);
return report;
}
Now, I am getting a different error
The model item passed into the dictionary is of type 'ICS20web.Models.IndexViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ICS20web.Models.IndexViewModel]'
I feel like I am close . . . but no cigar.

Multiple partial views in a strongly typed view (ASP.NET MVC5) ? Unable to get relative Path In View

I am having an issue that after saving relative path I cannot get picture in a list, and having error:
CS1061
'IEnumerable<tbl_Advertisement>' does not contain a definition for 'Imagepath' and no extension method 'Imagepath' accepting a first argument of type 'IEnumerable<tbl_Advertisement>' could be found (are you missing a using directive or an assembly reference?) GawadarHubUI C:\Users\Omer FarooQ\Desktop\GawadarHubistan\GawadarHubUI\GawadarHubUI\Areas\Common\Views\SampleViewAD\Index.cshtml
73
Active
This rrror in just view line: #Html.DisplayNameFor(model => Model.ImagePath) that after type Model. I cannot get the the property Name ImagePath, rather it's showing me Extension methods and methods
Controller CODE
using BLL;
using BOL;
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GawadarHubUI.Areas.Common.Controllers
{
[AllowAnonymous]
public class SampleViewADController : Controller
{
GawadarHubDbEntities db = new GawadarHubDbEntities();
private AdBl objbl;
public SampleViewADController()
{
objbl = new AdBl();
}
// GET: Common/SampleViewAD
[HttpGet]
public ActionResult Index()
{
try
{
var urls = objbl.GetAll().Where(x => x.isapproved == "A").ToList();
return View(urls);
}
catch (Exception e1)
{
TempData["Msg"] = "Approve Failed : " + e1.Message;
return RedirectToAction("Index");
}
}
}
}
View code:
#model IEnumerable<BOL.tbl_Advertisement>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#if (TempData["Msg"] != null)
{
<div class="alert alert-dismissable alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
#TempData["Msg"].ToString()
</div>}
<p>
#Html.ActionLink("SampleViewADController", "urls")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.adtitle)
</th>
<th>
#Html.DisplayNameFor(model => model.adsociety)
</th>
<th>
#Html.DisplayNameFor(model => model.addesc)
</th>
<th>
#Html.DisplayNameFor(model => model.isapproved)
</th>
<th>
#Html.DisplayNameFor(model => model.contactNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.ImagePath)
</th>
<th>
#Html.DisplayNameFor(model => model.price)
</th>
<th>
#Html.DisplayNameFor(model => model.Size)
</th>
<th>
#Html.DisplayNameFor(model => model.tbl_Category.cname)
</th>
<th>
#Html.DisplayNameFor(model => model.tbl_User.useremail)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.adtitle)
</td>
<td>
#Html.DisplayFor(modelItem => item.adsociety)
</td>
<td>
#Html.DisplayFor(modelItem => item.addesc)
</td>
<td>
#Html.DisplayFor(modelItem => item.isapproved)
</td>
<td>
#Html.DisplayFor(modelItem => item.contactNumber)
</td>
<td>
#Html.DisplayFor(model => Model.ImagePath)
</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
<td>
#Html.DisplayFor(modelItem => item.Size)
</td>
<td>
#Html.DisplayFor(modelItem => item.tbl_Category.cname)
</td>
<td>
#Html.DisplayFor(modelItem => item.tbl_User.useremail)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.adid }) |
#Html.ActionLink("Details", "Details", new { id = item.adid }) |
#Html.ActionLink("Delete", "Delete", new { id = item.adid })
</td>
</tr>
}
</table>
Try to replace
#Html.DisplayFor(model => Model.ImagePath)
with
<img src= "#Url.Content(item.ImagePath)" alt="Image" />
Should work.
Your define that your model is a collection:
#model IEnumerable<BOL.tbl_Advertisement>
So every time you write Model., you are referencing this collection.
The collection (IEnumerable<BOL.tbl_Advertisement>) has no property for Imagepath, as the error message tells you.
IEnumerable<tbl_Advertisement> does not contain a definition for Imagepath
Rather, the elements (tbl_Advertisement) of the collection have this property.
This is what Stephen and Igor meant when they wrote that you need to access the Imagepath through the elements of the collection.
Either by looping over the collection:
#foreach (var item in Model) {
<img src= "#Url.Content(item.ImagePath)" alt="Image" />
}
Or for the first element only:
var imagePath = Model.ElementAt(0).ImagePath;

passed into the dictionary is of type 'System.Collections.Generic.List`but this dictionary requires'System.Collections.Generic.IEnumerable` [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'm tryng to show a list of my customers in my view i got this error
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[PDF.View_model.Customers]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
in fill my list in the model layer and pass it throw pdf.view_model.View_model which is
public IEnumerable<Customers> GetAllCustomers(int? _id)
{
Ref_customers = new List<Customers>();
CList = new List<Models.EF_Model.Customer>();
foreach (var item in CList)
{
Ref_customers.Add(new Customers() { id = item.Id, FName = item.FName, LName = item.LName, Paid = item.Paid });
}
return Ref_customers;
and in my model
` public List<EF_Model.Customer> GetAllCustmers(int? _id)
{
using (var Context = new EF_Model.CoolerEntities())
{
return (_id.HasValue ? Context.Customers.Where(p => p.Id == _id).ToList() : Context.Customers.ToList());
}
}`
and finally in my Controller
`
public ActionResult Index(int? id)
{
Ref_ViewModel = new View_model.View_Model();
return View(Ref_ViewModel.GetAllCustomers(id));
}
`
and in my view i posted a small amount of it,it show a list of customers in the end by a foreach statement
`
#model IEnumerable<PDF.View_model.Customers>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FName)
</th>
<th>
#Html.DisplayNameFor(model => model.LName)
</th>
<th>
#Html.DisplayNameFor(model => model.Paid)
</th>
<th>
#Html.DisplayNameFor(model => model.Password)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Paid)
</td>
<td>
#Html.DisplayFor(modelItem => item.Password)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</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>
model.customer is simply a DTO of my table i also have one in my view_model.Customer
how can i convert list to IEnumerable ?i know a list is IEnumrable just don't know what to do
i'm confused
You seem to be having 2 Customer classes. You are passing one type from the controller and using the other one as Model in your View.
Either you need to update your View to use the other Type PDF.View_model.Customers, or make the controller pass ViewModel of Type PDF.Models.EF_Model.Customer
Your list indeed is IEnumerable<PDF.View_model.Customers>, but what you need is IEnumerable<PDF.Models.EF_Model.Customer>.
It's not the List that's not matching, it's its generic parameter.

Passing a list to aview in asp mvc : List vs IEnumerable

Just a quick question.
#using MvcApplication6.Models;
#model IEnumerable<Employee>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New record", "Create")
</p>
<p>#Html.ActionLink("Check departments", "Index", "Department")</p>
<table border="1">
<tr>
<th>
#Html.DisplayNameFor(model => model.id)
</th>
<th>
#Html.DisplayNameFor(model => model.firstname)
</th>
<th>
#Html.DisplayNameFor(model => model.lastname)
</th>
<th>
#Html.DisplayNameFor(model => model.gender)
</th>
<th>
#Html.DisplayNameFor(model => model.department)
</th>
<th>Action</th>
</tr>
#foreach (Employee item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.id)
</td>
<td>
#Html.DisplayFor(modelItem => item.firstname)
</td>
<td>
#Html.DisplayFor(modelItem => item.lastname)
</td>
<td>
#Html.DisplayFor(modelItem => item.gender)
</td>
<td>
#Html.DisplayFor(modelItem => item.department)
</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 }) |
#Html.DisplayFor(modelItem => item.Players[0])
</td>
</tr>
}
</table>
And this is how i passed my list:
public ActionResult Index()
{
EmployeeContext emp = new EmployeeContext();
List<Employee> adep = emp.Employees.ToList();
return View(adep);
}
Why do i have to declare it as IEnumerable on my view even though the one that i am passing is just a List ? Like if i will change IEnumerable to List, i will get errors specifically on this line of code:
#Html.DisplayNameFor(model => model.id)
I was testing it on my other views and it's declared as a list :
#model List<MvcApplication6.Models.Employee>
It works as intended although no DisplayNameFor and DisplayFor are involved.
IEnumerable
You can use IEnumerable<T> when you only need iteration (See here for a full list: https://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx), It means that If all you want to do with the list is foreach, you should return an IEnumerable<T>.
List
You can use List<T> for a list of objects that needs to be iterated through, modified, sorted, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).

Categories

Resources