Viewmodel not working correctly MVC error - c#

Any help would be great. I have recently started a project in MVC to store some client details, I created the model, controller and then right-clicked Add View. I am relatively new and I am trying to show the results of a query in a list view but getting the following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType148[System.String,System.String,System.Nullable1[System.DateTime],System.String,System.String,System.String,System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[cc_proj.ViewModels.HomeDashboardViewModel]'.
Controller:
[HttpGet]
public ActionResult Dash()
{
using (var context = new CRM_businessdevelopmentEntities())
{
var data =
(from Clients in context.Clients
join Sizes in context.Sizes on new { SizeID = (int)Clients.SizeID } equals new { SizeID = Sizes.SizeID }
join CampaignTypes in context.CampaignTypes on new { CampaignTypeID = (int)Clients.CampaignTypeID } equals new { CampaignTypeID = CampaignTypes.CampaignTypeID }
join Countrys in context.Countrys on new { CountryID = (int)Clients.CountryID } equals new { CountryID = Countrys.CountryID }
join Contacts in context.Contacts on new { ContactID = (int)Clients.ContactID } equals new { ContactID = Contacts.ContactID }
join Stages in context.Stages on new { StageID = (int)Clients.StageID } equals new { StageID = Stages.StageID }
where
Clients.Active == "True"
orderby
Clients.DateAdded descending
select new
{
Stage = Stages.Description,
Name = Clients.Name,
DateAdded = Clients.DateAdded,
Contact = Contacts.Contact,
Location = Countrys.Country,
CampaignType = CampaignTypes.Description,
Size = Sizes.Description,
Notes = Clients.Notes
}).ToList();
return View(data);
}
}
ViewModel:
public class HomeDashboardViewModel
{
[Key]
public int ClientID { get; set; }
public string Stage { get; set; }
public string Name { get; set; }
public DateTime DateAdded { get; set; }
public string Contact { get; set; }
public string Location { get; set; }
public string CampaignType { get; set; }
public string Size { get; set; }
public string Notes { get; set; }
public string Active { get; set; }
}
View:
#model IEnumerable<Business_Development_CRM.ViewModels.HomeDashboardViewModel>
#{
ViewBag.Title = "Dash";
}
<h2>Dash</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Stage)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.DateAdded)
</th>
<th>
#Html.DisplayNameFor(model => model.Contact)
</th>
<th>
#Html.DisplayNameFor(model => model.Location)
</th>
<th>
#Html.DisplayNameFor(model => model.CampaignType)
</th>
<th>
#Html.DisplayNameFor(model => model.Size)
</th>
<th>
#Html.DisplayNameFor(model => model.Notes)
</th>
<th>
#Html.DisplayNameFor(model => model.Active)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Stage)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateAdded)
</td>
<td>
#Html.DisplayFor(modelItem => item.Contact)
</td>
<td>
#Html.DisplayFor(modelItem => item.Location)
</td>
<td>
#Html.DisplayFor(modelItem => item.CampaignType)
</td>
<td>
#Html.DisplayFor(modelItem => item.Size)
</td>
<td>
#Html.DisplayFor(modelItem => item.Notes)
</td>
<td>
#Html.DisplayFor(modelItem => item.Active)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ClientID }) |
#Html.ActionLink("Details", "Details", new { id=item.ClientID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ClientID })
</td>
</tr>
}
</table>

try to fix the query, instead of a list of anonymous objects, create a list of ViewModel objects
var data =
(from Clients in context.Clients
.....
select new HomeDashboardViewModel
{
Stage = Stages.Description,
.....
}).ToList();

Related

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type System.Collections.Generic.IEnumerable'

How to solve this error ?
The model item passed into the dictionary is of type 'System.Data.EnumerableRowCollection1[System.Data.DataRow]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[AljawdahNewSite.Models.LAB_INVOICE_VIEW]'.
1- This is the Model :
public partial class LAB_INVOICE_VIEW
{
public int patient_no { get; set; }
public int order_id { get; set; }
public string patient_name { get; set; }
public int testid { get; set; }
public string testname { get; set; }
public string order_vat { get; set; }
public Nullable<decimal> total_amount { get; set; }
public string status_name { get; set; }
public Nullable<System.DateTime> COLLECTION_DATE { get; set; }
public Nullable<System.DateTime> RECEIVING_DATE { get; set; }
}
2- This is the controller :
public ActionResult Index(int id)
{
string sql = #"select patient_no ,
order_id ,
patient_name ,
testid ,
testname ,
order_vat ,
total_amount ,
status_name ,
COLLECTION_DATE ,
RECEIVING_DATE
FROM lab_invoice_view
where ORDER_ID = '{0}' ";
DataTable dt = func.fireDatatable(string.Format(sql, id));
LAB_INVOICE_VIEW invoice = new LAB_INVOICE_VIEW();
foreach (DataRow dr in dt.Rows)
{
invoice.patient_no = int.Parse(dr["patient_no"].ToString());
invoice.order_id = int.Parse(dr["order_id"].ToString());
invoice.patient_name = dr["patient_name"].ToString();
invoice.testid = int.Parse(dr["testid"].ToString());
invoice.testname = dr["testname"].ToString();
invoice.order_vat = dr["order_vat"].ToString();
invoice.total_amount = decimal.Parse(dr["total_amount"].ToString());
invoice.status_name = dr["status_name"].ToString();
invoice.COLLECTION_DATE = DateTime.Parse(dr["COLLECTION_DATE"].ToString());
invoice.RECEIVING_DATE = DateTime.Parse(dr["RECEIVING_DATE"].ToString());
}
return View(dt.AsEnumerable());
}
3- This is the view :
#model IEnumerable<AljawdahNewSite.Models.LAB_INVOICE_VIEW>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutMain.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.patient_no)
</th>
<th>
#Html.DisplayNameFor(model => model.order_id)
</th>
<th>
#Html.DisplayNameFor(model => model.patient_name)
</th>
<th>
#Html.DisplayNameFor(model => model.testid)
</th>
<th>
#Html.DisplayNameFor(model => model.testname)
</th>
<th>
#Html.DisplayNameFor(model => model.order_vat)
</th>
<th>
#Html.DisplayNameFor(model => model.total_amount)
</th>
<th>
#Html.DisplayNameFor(model => model.status_name)
</th>
<th>
#Html.DisplayNameFor(model => model.COLLECTION_DATE)
</th>
<th>
#Html.DisplayNameFor(model => model.RECEIVING_DATE)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.patient_no)
</td>
<td>
#Html.DisplayFor(modelItem => item.order_id)
</td>
<td>
#Html.DisplayFor(modelItem => item.patient_name)
</td>
<td>
#Html.DisplayFor(modelItem => item.testid)
</td>
<td>
#Html.DisplayFor(modelItem => item.testname)
</td>
<td>
#Html.DisplayFor(modelItem => item.order_vat)
</td>
<td>
#Html.DisplayFor(modelItem => item.total_amount)
</td>
<td>
#Html.DisplayFor(modelItem => item.status_name)
</td>
<td>
#Html.DisplayFor(modelItem => item.COLLECTION_DATE)
</td>
<td>
#Html.DisplayFor(modelItem => item.RECEIVING_DATE)
</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>
}
</table>
4- this is the actionlink when click the link :
<td>#Html.ActionLink("E-Invoice", "Index", "Invoice", new { id = item.LabOrders.ORDER_ID}, new { #class = "btn btn-primary", target = "_blank" })</td>
what I need to change in the code ?
I changed the way and used the dbcontext as the follwing code its solved my issue :
public ActionResult Index(int id)
{
var Invoice = db.LAB_INVOICE_VIEW.Where(c => c.order_id == id);
return View(Invoice);
}

ASP NET Core MVC database list view with sort all columns

I have a list view in my FileManager.cshtml page (code below) and I need to implement sort function to all columns that are displayed on this view. I looked through some examples on the web and YouTube but there are Javascript functions or "hand-made" namespaces. Is it possible to do it without JScript?
Thank you for help!
Function in my controller that displays list view from dbo.Files filtered by logged user ID:
private readonly TextCloudContext Context;
public IActionResult FileManager()
{
var user = _userManager.GetUserId(User);
var items = Context.Files.Where(f => f.UserID == user).ToList();
return View(items);
}
String in TextCloudContext.cs with get and set values in "Files" table from my SQL Server table "Files":
public DbSet<File> Files { get; set; }
File.cs model that initialize values for Db parameter in TextCloudContext and display column names in my FileManagerView.cshtml
public class File
{
public int Id { get; set; }
[Display(Name = "File Name")]
public string Name { get; set; }
public string Data { get; set; }
[Display(Name = "File Type")]
public string Extension { get; set; }
[Display(Name = "Date")]
public string Date { get; set; }
public string UserID { get; set; }
public TextCloudUser User { get; set; }
}
and finally View with table class:
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Extension)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th>
#Html.DisplayName("Actions")
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Extension)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td> - this razor Html doesn't work yet
#Html.ActionLink("Download", "Download", new { fileName = item.ToString() }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
Based on this docs,here is a working demo like below:
View:
#model IEnumerable<File>
<table class="table">
<thead>
<tr>
<th>
<a asp-action="FileManager" asp-route-sortOrder="#ViewData["NameSortParm"]">#Html.DisplayNameFor(model => model.Name)</a>
</th>
<th>
<a asp-action="FileManager" asp-route-sortOrder="#ViewData["ExtensionSortParm"]">#Html.DisplayNameFor(model => model.Extension)</a>
</th>
<th>
<a asp-action="FileManager" asp-route-sortOrder="#ViewData["DateSortParm"]">#Html.DisplayNameFor(model => model.Date)</a>
</th>
<th>
#Html.DisplayName("Actions")
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Extension)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.ActionLink("Download", "Download", new { fileName = item.ToString() }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
Controller:
public IActionResult FileManager(string sortOrder)
{
//var user = _userManager.GetUserId(User);
//var items = Context.Files.Where(f => f.UserID == user); //you may change this..
//for easy testing,i just create data manually..
var items = new List<File>()
{
new File(){ Id=1, Data="a", Date="2019-8-9", Extension=".jpg", Name="file1", UserID="1"},
new File(){ Id=1, Data="b", Date="2019-7-9", Extension=".png", Name="file2", UserID="2"},
new File(){ Id=1, Data="c", Date="2019-5-8", Extension=".png", Name="file3", UserID="3"},
new File(){ Id=1, Data="d", Date="2019-4-7", Extension=".jpg", Name="file4", UserID="4"}
}.AsQueryable();
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
ViewData["ExtensionSortParm"] = sortOrder == "Extension" ? "ext_desc" : "Extension";
switch (sortOrder)
{
case "name_desc":
items = items.OrderByDescending(s => s.Name);
break;
case "Date":
items = items.OrderBy(s => s.Date);
break;
case "date_desc":
items = items.OrderByDescending(s => s.Date);
break;
case "Extension":
items = items.OrderBy(s=>s.Extension);
break;
case "ext_desc":
items = items.OrderByDescending(s => s.Extension);
break;
default:
items = items.OrderBy(s => s.Name);
break;
}
return View(items);
}
Result:

One field in posted array not binding to model

I have the following, abridged for clarity and confidentiality, viewmodels:
public class BoqReviewViewModel
{
public List<BoqReviewItemViewModel> Items { get; set; } = new List<BoqReviewItemViewModel>();
}
public static BoqReviewItemViewModel FromEntity(GTT_BOQ_IMPORT import)
{
var ret = new BoqReviewItemViewModel();
ret.BOQ_IMPORT_ID = import.BOQ_IMPORT_ID;
ret.ITEM_CODE = import.ITEM_CODE;
ret.ITEM_DESC = import.ITEM_DESC;
ret.UNIT = import.UNIT;
ret.QTY = import.QTY;
ret.RATE = import.RATE;
ret.AMOUNT = import.AMOUNT;
ret.ITEM_PAYS = import.ITEM_PAYS;
ret.ITEM_CPA = import.ITEM_CPA;
return ret;
}
public GTT_BOQ_IMPORT ToEntity()
{
var ret = new GTT_BOQ_IMPORT();
ret.BOQ_IMPORT_ID = this.BOQ_IMPORT_ID;
ret.ITEM_CODE = this.ITEM_CODE;
ret.ITEM_DESC = this.ITEM_DESC;
ret.UNIT = this.UNIT;
ret.QTY = this.QTY;
ret.RATE = this.RATE;
ret.AMOUNT = this.AMOUNT;
ret.ITEM_PAYS = this.ITEM_PAYS;
ret.ITEM_CPA = this.ITEM_CPA;
return ret;
}
[Key]
public Guid BOQ_IMPORT_ID;
public string ITEM_CODE { get; set; }
public string ITEM_DESC { get; set; }
public string UNIT { get; set; }
public decimal? QTY { get; set; }
public decimal? RATE { get; set; }
public decimal? AMOUNT { get; set; }
public bool? ITEM_PAYS { get; set; }
public bool? ITEM_CPA { get; set; }
public bool IsFlagged { get; set; }
}
Then I have the following GET action for an index type view:
[HttpGet]
public ActionResult BoqReview()
{
var model = new BoqReviewViewModel();
model.CONTRACT_ID = Guid.NewGuid();
model.PROJECT_ID = Guid.NewGuid();
model.Items = GetItems().ToList();
return View(model);
}
Where GetItems is a method that returns an IEnumerable with three fully populated item level viewmodels. When I startup the app, I see a properly populated table with 3 rows with all columns properly populated.
This is the view:
#using (Html.BeginForm("BoqReview", "Boq", FormMethod.Post))
{
<table class="table">
<tr>
<th>
</th>
<th class="col-header">
Item Code
</th>
<th class="col-header">
Item Description
</th>
<th>
Unit
</th>
<th>
Quantity
</th>
<th>
Rate
</th>
<th>
Amount
</th>
<th>
Item Pays
</th>
<th>
Item CPA
</th>
<th>
</th>
</tr>
#for (var i = 0; i < Model.Items.Count; i++)
{
<tr>
<td>
#Html.TextBoxFor(model => model.Items[i].BOQ_IMPORT_ID)
</td>
<td>
#Html.TextBoxFor(model => Model.Items[i].ITEM_CODE)
#Html.ValidationMessageFor(model => Model.Items[i].ITEM_CODE)
</td>
<td>
#Html.TextBoxFor(model => Model.Items[i].ITEM_DESC)
#Html.ValidationMessageFor(model => Model.Items[i].ITEM_DESC)
</td>
<td>
#Html.TextBoxFor(model => Model.Items[i].UNIT, new {style = "width: 120px;"})
#Html.ValidationMessageFor(model => Model.Items[i].UNIT)
</td>
<td>
#Html.TextBoxFor(model => Model.Items[i].QTY)
#Html.ValidationMessageFor(model => Model.Items[i].QTY)
</td>
<td>
#Html.TextBoxFor(model => Model.Items[i].RATE)
#Html.ValidationMessageFor(model => Model.Items[i].RATE)
</td>
<td>
#Html.TextBoxFor(model => Model.Items[i].AMOUNT)
#Html.ValidationMessageFor(model => Model.Items[i].AMOUNT)
</td>
<td>
#Html.DropDownListFor(model => Model.Items[i].ITEM_PAYS, Model.YesNoSelectList)
#Html.ValidationMessageFor(model => Model.Items[i].ITEM_PAYS)
</td>
<td>
#Html.DropDownListFor(model => Model.Items[i].ITEM_CPA, Model.YesNoSelectList)
#Html.ValidationMessageFor(model => Model.Items[i].ITEM_CPA)
</td>
<td>
#Html.CheckBoxFor(model => Model.Items[i].IsFlagged)
</td>
</tr>
}
<tr>
<td colspan="4">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Everything looks perfect, yet when I submit the form:
[HttpPost]
public ActionResult BoqReview(BoqReviewViewModel model)
{
using (var db = new AppDbContext())
{
foreach (var modelItem in model.Items)
{
var updated = modelItem.ToEntity();
db.GttBoqImports.AddOrUpdate(updated);
}
db.SaveChanges();
}
return RedirectToAction("BoqReview");
}
The BOQ_IMPORT_ID field on each item viewmodel is an empty GUID, yet the displayed table shows a proper GUID. All other properties of the item level viewmodels are still populated.
What could be wrong that just this BOQ_IMPORT_ID is not properly model bound? When I debug the network call in Chrome tools, it shows a proper GUID value for each BOQ_IMPORT_ID in the form data posted:
Items[0].BOQ_IMPORT_ID: 610d9a12-920f-43aa-89bc-08b68067a462
Items[0].ITEM_CODE: AA1
Items[0].ITEM_DESC: Some A's and a 1
Items[0].UNIT: kg
Items[0].QTY: 200
...
JUST IN: Renaming the VM property in that class and in the view solved the whole problem. Maybe, despite several VS restarts, a machine restart mighty have somehow helped. This smells of temp files or some caching somewhere.

how to format a date time variable in asp.net mvc using #HTML.DisplayNameFor

I have this statement in my view that as follows:
<th>
#Html.DisplayNameFor(model => model.ReleaseDate)
</th>
all I'm trying to do is format the release date so that it will be in the format of mm/dd/yyyy. I've searched loads and haven't come across anything that is exactly what I'm looking for. Any help would be greatly appreciated, I'm relatively new to coding.
Here is my Model:
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace MvcMovie2.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public string Rating { get; set; }
public decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
public class DummyModel : Movie
{
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime ReleaseDate { get; set; }
}
}
and here is my view:
#model IEnumerable<MvcMovie2.Models.Movie>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayFor(model => model.ReleaseDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.Rating)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rating)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</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 can achieve that with the DisplayFormatAttribute :
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace MvcMovie2.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public string Rating { get; set; }
public decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}
Your view is strongly typed to IEnumerable<MvcMovie2.Models.Movie> therefore you cannot use the html helper like you did. Instead separate your code in partial views that are strongly type to MvcMovie2.Modes.Movie :
Code for the actual view :
#model IEnumerable<MvcMovie2.Models.Movie>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
#Html.Partial("Header")
#foreach (var item in Model)
{
#Html.Partial("Movie", item)
}
</table>
Code for the Header.cshtml partial view :
#model MvcMovie2.Models.Movie
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.Rating)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
Code for the Movie.cshtml partial view :
#model MvcMovie2.Models.Movie
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rating)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</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>
I got it to work. All I had to do was put this using clause in my model:
using System.ComponentModel.DataAnnotations;
then I put this line of code above my code that defined my Release Date:
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
and then it worked perfectly, I didn't have to change anything in the view.

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`

Model: StudentData (Model 1)
namespace Aug16.Models
{
[Table("Stdnt_Info")]
public class StudentData
{
[Key]
public long Stdnt_Id { get; set; }
public string Stdnt_Name { get; set; }
public string Stdnt_Fname { get; set; }
public string Stdnt_Address { get; set; }
public string Stdnt_Semmester { get; set; }
public DateTime Sem_StartDate { get; set; }
public DateTime Sem_EndDate { get; set; }
public int Stdnt_Mark1 { get; set; }
public int Stdnt_Mark2 { get; set; }
public int Stdnt_Mark3 { get; set; }
public Decimal Stdnt_Sem_Per { get; set; }
}
}
-------------------------------------------------------------------------------
DBContext Model: Aug16Data (Model2)
namespace Aug16.Models
{
public class Stdnt_Details : DbContext
{
public DbSet<StudentData> Student_Information { get; set; }
//public DbSet<Stdnt_Details> Student_Information { get; set; }
//public DbSet<Aug16Data> Stdnt_Mark { get; set; }
}
}
------------------------------------------------------------------------------
Controller : StudentDataController
namespace Aug16.Controllers
{
public class StudentDataController : Controller
{
//
// GET: /StudentData/
Aug16.Models.Stdnt_Details StoreDB = new Models.Stdnt_Details();
public ActionResult Aug16DataAction()
{
var StdDet = StoreDB.Student_Information.ToList();
return View(StdDet);
}
}
}
---------------------------------------------------------------------------
View: Aug16DataAction
#model IEnumerable<Aug16.Models.Stdnt_Details>
#{
ViewBag.Title = "Aug16DataAction";
}
<h2>Aug16DataAction</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<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>
}
</table>
Error as below
Server Error in '/' Application.
The model item passed into the dictionary is of type 'System.Collections.Generic.List[Aug16.Models.StudentData]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable[Aug16.Models.Stdnt_Details]'.
Please what is the solution for this error?
First, you need to change your model type, as mentioned on comments to your question.
However, you are looking an empty view because you don't have the code to show all the model properties. Try to change your view with this code:
#model IEnumerable<Test.Models.StudentData>
#{
ViewBag.Title = "Aug16DataAction";
}
<h2>Aug16DataAction</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Stdnt_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Stdnt_Fname)
</th>
<th>
#Html.DisplayNameFor(model => model.Stdnt_Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Stdnt_Semmester)
</th>
<th>
#Html.DisplayNameFor(model => model.Sem_StartDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Sem_EndDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Stdnt_Mark1)
</th>
<th>
#Html.DisplayNameFor(model => model.Stdnt_Mark2)
</th>
<th>
#Html.DisplayNameFor(model => model.Stdnt_Mark3)
</th>
<th>
#Html.DisplayNameFor(model => model.Stdnt_Sem_Per)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Stdnt_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stdnt_Fname)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stdnt_Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stdnt_Semmester)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sem_StartDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sem_EndDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stdnt_Mark1)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stdnt_Mark2)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stdnt_Mark3)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stdnt_Sem_Per)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Stdnt_Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Stdnt_Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Stdnt_Id })
</td>
</tr>
}
</table>

Categories

Resources