I am getting the following error
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType34[System.String,System.Int32,System.Int32,System.DateTime]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ControllerName]'.
I did the code migration (database update) after that I want to just list the items by column name My code is as follows
public ActionResult Index()
{
DB db = new DB();
var categorylist = from a in db.categories
select new
{
a.CategoryName,
a.ID,
a.stock,
a.EntryDate
};
return View(categorylist.ToList());
}
Any help would be appreciated
Thanks in advance.
View is as follows
#model IEnumerable<Categories.Models.Categories>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create") </p> <table class="table">
<tr>
<th>#Html.DisplayNameFor(model => model.CategoryName)</th>
<th>#Html.DisplayNameFor(model => model.stock)</th>
<th>#Html.DisplayNameFor(model => model.EntryDate)</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.CategoryName)</td>
<td>#Html.DisplayFor(modelItem => item.stock)</td>
<td>#Html.DisplayFor(modelItem => item.EntryDate)</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>
To take advantage of the model binding features of MVC you should create a view model which represents those the properties you want to display and/or edit (adjust property types as required)
public class CategoryVM
{
public int ID { get; set; }
public string CategoryName { get; set; }
public int Stock { get; set; }
public DateTime EntryDate { get; set; }
}
and change you method to
public ActionResult Index()
{
DB db = new DB();
var categorylist = (from a in db.categories
select new CategoryVM
{
CategoryName = a.CategoryName,
ID = a.ID,
Stock = a.stock,
EntryDate = a.EntryDate
}).ToList();
return View(categorylist);
}
View
#model List<CategoryVM>
<table>
<thead>
<tr>
<th>Category Name</th>
<th>stock</th>
<th>Entry Date</th>
...
</tr>
</thead>
<tbody>
#foreach(var item in Model)
{
<tr>
<td>#Html.DisplayFor(m => item.ID)<td>
<td>#Html.DisplayFor(m => item.CategoryName)</td>
...
</tr>
}
</tbody>
</table>
I think you need to Change the model type thar you defined in your view
Edit: Try
#model IList<dynamic>
Related
Entities:
public partial class Institution
{
public int? Id { get; set; }
public string? District { get; set; }
public string? InstitutionCode { get; set; }
public string? InstitutionName { get; set; }
public string? DemolitionStatus { get; set; }
public string? ReinforcementStatus { get; set; }
}
Controller:
public class HomeController : Controller
{
_context c;
public HomeController(_context c)
{
this.c = c;
}
public IActionResult Index()
{
var GetAll=c.Institutions.ToList();
return View(GetAll);
}
}
In View
#model List<GetAll>
#foreach (var item in Model)
{
#item.InstitutionName
}
Also it doesn't work:
The type or namespace name 'GetAll' could not be found
Try with #model SolutionName.Entities or Ienumarable or adding namespace #using FBMv3.Controllers
What is the wrong or missing?
Try with #model SolutionName.Entities or Ienumarable or adding
namespace #using FBMv3.Controllers
What is the wrong or missing?
Well, first of all, GetAllcannot be a reference for your Institution list.
assuming, you are using asp.net core application, in this scenario, here #model List<GetAll> should be the location of your Institution class. For instance if your Institution class located like below folder:
So you should write the code like this #model IEnumerable<DotNet6MVC.Models.Institution> instead of #model List<GetAll>
Complete sample for you:
Controller:
public IActionResult Index()
{
var instituteList = new List<Institution>()
{
new Institution(){ Id =101,District = "Dis-A", InstitutionCode = "IC-1",InstitutionName = "IN-AAA",DemolitionStatus="YES",ReinforcementStatus = "T"},
new Institution(){ Id =102,District = "Dis-B", InstitutionCode = "IC-2",InstitutionName = "IN-BBB",DemolitionStatus="NO",ReinforcementStatus = "F"},
new Institution(){ Id =103,District = "Dis-C", InstitutionCode = "IC-3",InstitutionName = "IN-CCC",DemolitionStatus="NO",ReinforcementStatus = "T"},
new Institution(){ Id =104,District = "Dis-D", InstitutionCode = "IC-4",InstitutionName = "IN-DDD",DemolitionStatus="NO",ReinforcementStatus = "T"},
new Institution(){ Id =105,District = "Dis-E", InstitutionCode = "IC-5",InstitutionName = "IN-EEE",DemolitionStatus="YES",ReinforcementStatus = "T"},
};
return View(instituteList);
}
Note: You could write your controller code as well. Like this:
var GetAll=c.Institutions.ToList();
return View(GetAll)
View:
#model IEnumerable<DotNet6MVC.Models.Institution>
#{
ViewData["Title"] = "Index";
}
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.District)
</th>
<th>
#Html.DisplayNameFor(model => model.InstitutionCode)
</th>
<th>
#Html.DisplayNameFor(model => model.InstitutionName)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.District)
</td>
<td>
#Html.DisplayFor(modelItem => item.InstitutionCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.InstitutionName)
</td>
<td>
<a asp-action="EditMember" class="btn btn-primary" asp-route-memberId="#item.Id">Details</a> | <a asp-action="EditMember" class="btn btn-warning" asp-route-memberId="#item.Id">Edit</a>
</td>
</tr>
}
</tbody>
</table>
Note: Be double confirm in your scenario, it would be #model IEnumerable<YourProjectName.YourClassFolder.Institution>. Because, your problem is here.
Output:
Note: If you still have any concern on this I would highly recommend you to check this official document.
still learning MVC (slowly) which I am enjoying but having some trouble with partial views. If anyone could point me in the right direction that would be great!
This is the error I am getting:
InvalidOperationException: The model item passed into the dictionary
is of type
'System.Collections.Generic.List1[mvc_project.Models.Contact]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[mvc_project.ViewModels.ViewContactsVM]'.
I created the partial view using the List template.
Chose my model ViewContactsVM
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace mvc_project.ViewModels
{
public class ViewContactsVM
{
[Key]
public int ContactID { get; set; }
public int ClientID { get; set; }
[DisplayName("Contact Name")]
public string ContactName { get; set; }
[DisplayName("Contact Phone Number")]
public string ContactPhoneNumber { get; set; }
[DisplayName("Contact Email Address")]
public string ContactEmailAddress { get; set; }
[DisplayName("Job Title")]
public string JobTitle { get; set; }
public string AddedBy { get; set; }
}
}
Controller code:
public ActionResult _ContactList(int id)
{
using (var context = new mvc_projectEntities())
{
var data = context.Contacts.Where(x => x.ClientID == id).ToList();
return View(data);
}
}
_ContactsList Partial View Page:
#model IEnumerable<mvc_project.ViewModels.ViewContactsVM>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ClientID)
</th>
<th>
#Html.DisplayNameFor(model => model.ContactName)
</th>
<th>
#Html.DisplayNameFor(model => model.ContactPhoneNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.ContactEmailAddress)
</th>
<th>
#Html.DisplayNameFor(model => model.JobTitle)
</th>
<th>
#Html.DisplayNameFor(model => model.AddedBy)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ClientID)
</td>
<td>
#Html.DisplayFor(modelItem => item.ContactName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ContactPhoneNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.ContactEmailAddress)
</td>
<td>
#Html.DisplayFor(modelItem => item.JobTitle)
</td>
<td>
#Html.DisplayFor(modelItem => item.AddedBy)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ContactID }) |
#Html.ActionLink("Details", "Details", new { id=item.ContactID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ContactID })
</td>
</tr>
}
</table>
Details View Page:
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
#Html.Action("_ContactList")
It is necessary to pass the ViewContactsVM type to the view, as it defined in the view data model. Therefore try:
public ActionResult _ContactList(int id)
{
using (var context = new mvc_projectEntities())
{
var data = context.Contacts
.Where(x => x.ClientID == id)
.Select(c => new mvc_project.ViewModels.ViewContactsVM() {
ContactID = c.ContactID,
ClientID = c.ClientID,
ContactName = c.ContactName
...
})
.ToList();
return View(data);
}
}
I get this error:
The call is ambiguous between the following methods or properties:
DisplayNameFor<IEnumerable<Category>,string>(HtmlHelper<IEnumerable<Category>>, System.Linq.Expressions.Expression<System.Func<IEnumerable,string>>)
and
DisplayNameFor<Category,string>(HtmlHelper<IEnumerable>, System.Linq.Expressions.Expression<System.Func<Category,string>>)
My model is
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
My Context Model is
public class CategoryContext : DbContext
{
public DbSet<Category> category { get; set; }
}
My Controller is :
public ActionResult GetCategory()
{
using (CategoryContext cc = new CategoryContext())
{
var cat = cc.category.ToList();
return View();
}
}
My View is :
#model IEnumerable<CRUD_Manav_EF.Models.Category>
<h1>Get Category</h1>
<table>
<tr>
<th>#Html.DisplayNameFor(model => model.CategoryName)</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayNameFor(modelItem => item.CategoryName) // I get error here
</td>
<td>
#Html.ActionLink("Edit", "Update", new { id = item.CategoryId })
#Html.ActionLink("Details", "Details", new { id = item.CategoryId })
#Html.ActionLink("Delete", "Delete", new { id = item.CategoryId })
</td>
</tr>
}
</table>
This error is displaying because you have used
#Html.DisplayNameFor(model => model.CategoryName) in table foreach loop and call would ambiguous between those method mentioned above. Since there is no benefit of using Display name again and again while iterating. if you will see the whole description of #Html.DisplayNameFor() you will get that the first parameter accept only model(lambda expression) and not IEnumerable of model. This is also shown in your compiler error.
see in example screenshot (this is dummy project)
Use #html.DisplayFor(..) instead in your foreach loop.
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CategoryName)
</td>
<td>
#Html.ActionLink("Edit", "Update", new { id = item.CategoryId })
#Html.ActionLink("Details", "Details", new { id = item.CategoryId })
#Html.ActionLink("Delete", "Delete", new { id = item.CategoryId })
</td>
</tr>
}
This htmlhelper method will take IEnumerable of your model. And your issue will be resolved(you can check it yourself).
I am new to MVC and now stuck in a serious problem. it is for me, very serious
I need to load a view with a list of meetings (which is loading fine) in html , I have added a checkbox to each row also. Now I need to save to the database ,only the checked values. But the controller is returning null when posting.. Really stuck and cant find a solution.
Pls see code below which I have done
Model
public class aMeet
{
public List<AcceptedRecords> amList { get; set; }
public static List<AcceptedRecords> GetamList()
{
DataSet ds = new DataSet();
List<AcceptedRecords> resultlist = new List<AcceptedRecords>();
using (cmd)
{
cmd.CommandText = #"SELECT Line_code,person_code,person_address from tbl where meeting_code =859489;
ds = cmd.ExecuteDataSet();
}
if (!Utils.IsDataSetEmpty(ds))
{
AcceptedRecords tpmApp;
foreach (DataRow row in ds.Tables[0].Rows)
{
tpmApp = new AcceptedRecords();
tpmApp = tpmApp.LoadRecords(row);
resultlist.Add(tpmApp);
}
}
return resultlist;
}
}
Model
public class AcceptedRecords
{
public int line_Code { get; set; }
public string person_Name { get; set; }
public string person_Address { get; set; }
public bool extra_checked { get; set; }
}
View
#model projct.Models.aRecs
#using (Html.BeginForm("AddRecord","Home"))
{
<table id="tbl" style ="width:100%" cellpadding="0" cellspacing="0" class="race-fields">
<thead>
<tr>
<th style="width:500px">line code</th>
<th style="width:100px">name</th>
<th style="width:500px">address</th>
<th style="width:500px">extra</th>
</tr>
</thead>
<tbody>
<tr>
#for (int i = 0; i < Model.amList.Count; i++)
{
<tr class="EvenRow">
<td>
#Html.DisplayFor(m => m.amList[i].line_Code) </td>
<td>#Html.DisplayFor(m => m.amList[i].person_name) </td>
<td>#Html.DisplayFor(m => m.amList[i].person_address) </td>
<td>
#Html.CheckBoxFor(m => m.amList[i].extra_checked) </td>
</tr>
}
</tr>
<tr>
<span>
<input type="submit" Value ="Save"/>
</span>
</tr>
</tbody>
</table>
}
Controller
[HttpPost]
public ActionResult AddRecord(List<aMeet> spm)
{
if (spm == null)
throw new ApplicationException("No Parameters passed to Create");
int? appID = 0;
return Json(appID);
}
}
--- It Is triggering to controller on Save but model [spm] is null.
How to get this corrected. Here I need to save to database the tr elements that are checked. Please request any help. I have tried a lot of things but the model is always null/
Many thanks
Assuming your aRecs class has a amList property which is a list of AcceptedRecords
public class aRecs
{
public List<AcceptedRecords> amList { set; get; }
}
Assuming line_code value is a unique (may be primary key) to get a record from your corresponding table, In your view, you need to keep the line_code property value of each item in amList in a hidden field so that when the form is submitted you will get this value and using that you can query the corresponding record and update it.
#model YourNamespaceHere.aRecs
#using (Html.BeginForm("AddRecord","Home"))
{
<table>
#for (int i = 0; i < Model.amList.Count; i++)
{
<tr class="EvenRow">
<td>
#Html.DisplayFor(m => m.amList[i].line_Code)
</td>
<td>#Html.DisplayFor(m => m.amList[i].person_Name) </td>
<td>
#Html.CheckBoxFor(m=>m.amList[i].extra_checked)
#Html.HiddenFor(m => m.amList[i].line_Code)
</td>
</tr>
}
</table>
<input type="submit"/>
}
And in your HttpPost action, your parameter will be a single object of aRecs
[HttpPost]
public ActionResult AddRecord(aRecs model)
{
foreach (var item in model.amList)
{
var lineCode = item.line_Code;
var isChecked = item.extra_checked;
/// get the record using lineCode and update the record.
}
return RedirectToAction("Index");
}
I am learning MVC and display a list of products in a view.
#model IEnumerable<Domain.Model.Product>
<table>
<tr>
<th style="width:50px; text-align:left">Id</th>
<th style="text-align:left">Name</th>
<th style="text-align:left">Category</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category.Name)
</td>
</tr>
}
</table>
The products belong to categories, which are displayed in the right column. I now want to filter the products by categories, for which I would like to use a dropdownlist control. I found #Html.DropDownListFor(), but as far as I understand, this will only give me properties of the currently underlying model (Product).
My controller:
public class ProductController : Controller
{
ProductRepository pr = new ProductRepository();
public ActionResult Default()
{
List<Product> products = pr.GetAll();
return View("List", products);
}
}
You could do something like this. Just create a class with the info that you need.
public class ProductsModel
{
public ProductsModel() {
products = new List<Product>();
categories = new List<SelectListItem>();
}
public List<Product> products { get;set; }
public List<SelectListItem> categories { get;set; }
public int CategoryID { get;set; }
}
Then your controller:
public class ProductController : Controller
{
ProductRepository pr = new ProductRepository();
public ActionResult Default()
{
ProductsModel model = new ProductsModel();
model.products = pr.getAll();
List<Category> categories = pr.getCategories();
model.categories = (from c in categories select new SelectListItem {
Text = c.Name,
Value = c.CategoryID
}).ToList();
return View("List", model);
}
}
Finally, your view
#model IEnumerable<Domain.Model.ProductsModel>
#Html.DropDownListFor(m => model.CategoryID, model.categories)
<table>
<tr>
<th style="width:50px; text-align:left">Id</th>
<th style="text-align:left">Name</th>
<th style="text-align:left">Category</th>
</tr>
#foreach (var item in Model.products) {
<tr>
<td>
#item.Id
</td>
<td>
#item.Name
</td>
<td>
#item.Category.Name
</td>
</tr>
}
</table>