I have two unrelated tables. I want to display data from them to my view. I tried to add a class to bring the data to it like the following:
public class OrderViewData
{
public List<EventHome> Events { get; set; }
public List<Portfolio> Portfolio{ get; set; }
}
EventHome and Portfolio are my tables's names
then I used LinQ select in my Controller to get my list and send it to the view
like this
ToddlerEntities db=new ToddlerEntities();
public ActionResult Index()
{
OrderViewData orderView = new OrderViewData();
orderView.Events = (from o in db.EventHome select o).ToList();
orderView.Portfolio = (from o in db.Portfolio select o).ToList();
return View(orderView);
}
and in my view I tried to bring my list
#model List<Toddlers.Models.OrderViewData>
and
#foreach (var ev in Model)
{
#Html.DisplayFor(modelItem => ev.Events.EventsImg)
}
but I get the following error
The model item passed into the dictionary is of type 'Toddlers.Models.OrderViewData', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Toddlers.Models.OrderViewData]
Your passing a single instance of OrderViewData to the view so your view needs to be
#model Toddlers.Models.OrderViewData
and then loop through its collections
#foreach (var ev in Model.Events)
{
#Html.DisplayFor(m => ev.EventsImg)
}
Side note: There is no real need to make the collections List<T> - they could just be IEnumarable<T>
Related
I am working on a project in which, i am getting the client names from database table using the HomeController>Index Action method.
I want to send this list to Index view and display this list in the dropdownlist.
Request you to please help me with the View accordingly as i am new to MVC.
Home Controller
public ActionResult Index()
{
var model = from c in
_mdlCntxtcls.clients
where (DateTime.Now<=c.End_Date)
select c;
return View(model);
}
Model
public class Client
{
public int ClientID { get; set; }
public string Client_Names { get; set; }
public DateTime Start_Date { get; set; }
public DateTime End_Date { get; set; }
}
Please help as early as possible
Thank you
You are passing a collection of Client objects to the view. So your view should be strongly typed to a collection of Client object to accept that as the (view) model data.
You can use the DropDownList html helper method to render a SELECT element from this view model data. You can create a SelectList object from this collection (your page model)
#model IEnumerable<YourNamespaceHere.Client>
#Html.DropDownList("StudentSelect",new SelectList(Model,"ClientID","Client_Names"))
This will render a SELECT element with name attribute value set to StudentSelect. Each options in the SELECT elemtn will have the ClientID as the value attribute value and Client_Names property value as the option text.
You can also use viewbag or viewdata for send list of Client from controller to view and then you can put it in dropdown list.
In Controller you can use like :
List<SelectListItem> ClientList = new List<SelectListItem>();
using (dbContext db = new dbContext())
{
var Clients = db.Client.ToList();
foreach (var i in Clients)
{
ClientList.Add(new SelectListItem { Text = i.Client_Name, Value = i.ClientID.ToString() });
}
}
ViewBag.ClientList = ClientList;
and in view side you can use that viewbag like :
#Html.DropDownListFor(x => x.Client, (IEnumerable<SelectListItem>)ViewBag.ClistList)
How can this nested grouping be implemented in razor view?
This is what i have tried
Controller
public ActionResult SeniorityList()
{
var employee = db.Employees.GroupBy(f => f.Facility.FacilityName).ToList();
return View(employee.ToList());
}
However I don't know how to implement the foreach loop in view
Since you want the grouped data, i suggest you create a new class for that
public class GroupedItem
{
public string GroupName { set; get; }
public IEnumerable<Employee> Items { set; get; }
}
Now you can use the GroupBy method on your db.Employees collection and project the results to a collection of GroupedItem class objects.
var grouped = db.Employees
.GroupBy(f => f.Facility.FacilityName,i=>i,
(key,v)=>new GroupedItem { GroupName = key,Items = v})
.ToList();
return View(grouped);
the type of grouped variable will be a list of GroupedItem and we are passing that to the view. So make sure that your view is strongly typed to a collection of GroupedItem class.
#model IEnumerable<GroupedItem>
#foreach (var group in Model)
{
<h3>#group.GroupName</h3>
foreach (var p in group.Items)
{
<p>#p.Name</p>
}
}
I tried to pass 2 tables from Controller to view by using ViewModel
I declared:
public class Temp
{
public Models.ORDER_HEADER_INFO ORDER_HEADER_INFO { get; set; }
public Models.ORDER_ROUTING_DETAIL ORDER_ROUTING_DETAIL { get; set; }
}
In controller I write:
public ActionResult DataLoading()
{
using (Models.AllDataEntities et = new Models.AllDataEntities())
{
var Odata = (from ord in et.ORDER_ROUTING_DETAIL join
oh in et.ORDER_HEADER_INFO on ord.ORDER_NO equals oh.ORDER_NO
orderby ord.TARGET_COMPLETION_FLAG,oh.PRODUCT_START_DATE
select new {Order_No = oh.ORDER_NO,ROUTING_NAME = ord.ROUTING_NAME,
PJNO = oh.PJNO,DELIVERY_DESTINATION = oh.DELIVERY_DESTINATION,
}).ToList();
return View(Odata);
}
}
In view:
<table>
#for (int i = 0; i < Model.Count; i++ )
{
<tr>
<td>#Html.DisplayFor(m=>m[i].ORDER_HEADER_INFO.ORDER_NO)</td>
<td>#Html.DisplayFor(m=>m[i].ORDER_HEADER_INFO.PJNO)</td>
<td>#Html.DisplayFor(m=>m[i].ORDER_ROUTING_DETAIL.ROUTING_NAME)</td>
<td>#Html.DisplayFor(m=>m[i].ORDER_HEADER_INFO.DELIVERY_DESTINATION)</td>
</tr>
}
</table>
When i run the code, there is the exception like this:
The model item passed into the dictionary is of type
'System.Collections.Generic.List1[<>f__AnonymousType34[System.String,System.String,System.String,System.String]]',
but this dictionary requires a model item of type
'System.Collections.Generic.List`1[TIS.Models.Temp]'.
When I debug, Data is completely loaded to Odata, but I cannot understand what type of Odata.
You need to have this select statement. Instead of Anonymous Type, Select new Temp() { ... }. Reason is that your View Expects List<temp>, but you are passing list<AnonymousType> from controller.
var Odata = (from ord in et.ORDER_ROUTING_DETAIL join
oh in et.ORDER_HEADER_INFO on ord.ORDER_NO equals oh.ORDER_NO
orderby ord.TARGET_COMPLETION_FLAG,oh.PRODUCT_START_DATE
select new Temp() {ORDER_HEADER_INFO = oh, ORDER_ROUTING_DETAIL = ord }).ToList();
If you dont not want to use all the properties in the entities, then you need to create your DTO with the properties you want to use and map them in the linq query.
Your server side code should instantiate the Temp object while creating the list:
public ActionResult DataLoading()
{
using (Models.AllDataEntities et = new Models.AllDataEntities())
{
var Odata = (from ord in et.ORDER_ROUTING_DETAIL join
oh in et.ORDER_HEADER_INFO on ord.ORDER_NO equals oh.ORDER_NO
orderby ord.TARGET_COMPLETION_FLAG, oh.PRODUCT_START_DATE
select new Temp()
{
ORDER_HEADER_INFO = new ORDER_HEADER_INFO()
{
ROUTING_NAME = ord.ROUTING_NAME
},
ORDER_ROUTING_DETAIL = new ORDER_ROUTING_DETAIL()
{
Order_No = oh.ORDER_NO
}
}).ToList();
return View(Odata);
}
}
Your view can operate on this list like so:
#model IEnumerable<MvcApplication16.Models.Temp>
<table>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(item.ORDER_HEADER_INFO.ORDER_NO)</td>
<td>#Html.DisplayFor(item.ORDER_HEADER_INFO.PJNO)</td>
<td>#Html.DisplayFor(item.ORDER_ROUTING_DETAIL.ROUTING_NAME)</td>
<td>#Html.DisplayFor(item.ORDER_HEADER_INFO.DELIVERY_DESTINATION)</td>
</tr>
}
</table>
Note: As in your original Temp object definition, you have mapped entity directly, LINQ will throw error as you mentioned in the comment.
The entity or complex type 'Model.ORDER_HEADER_INFO' cannot be
constructed in a LINQ to Entities query.
You cannot (and should not be able to) project onto a mapped entity. You can, however, project onto an anonymous type or onto a DTO.
I suggest you create you modify your Temp definition and include properties that your want to send to view. That will make it a ViewModel object which is the right approach.
public class Temp
{
public string ORDER_NO { get; set; }
public string ROUTING_NAME { get; set; }
}
My application has multiple areas within one facility. I am trying to pass a single model to the view that contains facility values (facility_id, facility_name), and a list of areas. I currently have the list of areas as a type of the entity model for the table (area_list).
My viewmodel is as follows:
public class AreaView
{
public string facility_name { get; set; }
public int facility_id { get; set; }
public int group_id { get; set; }
public IList<area_list> areas { get; set; }
}
As an aside, I had originally tried setup the list of areas as a separate viewmodel (AreaS) instead of the model area_list, but I had other issues there so went back to directly referencing the for simplicity. I am assuming this would be more appropriate...
My Controller:
public ActionResult List(int id = 0)
{
var model = (from f in areaDB.facility_list
where f.facility_id == id
select new AreaView
{
facility_id = f.facility_id,
facility_name = f.facility_name,
areas = (from a in areaDB.area_list
orderby a.area_name
where a.facility_id == id
select a).ToList()
});
return View(model);
}
My View (abbreviated):
#model SkyeEnergy.Models.AreaView
Facility: #Model.facility_name
#foreach (var item in Model.areas) {
<tr>
<td>
#Html.ActionLink(item.vendor_name,"Details","Area",new {id = item.vendor_id},null)
</td>
</tr>
}
I have tried numerous variations to accomplish what's below, which has given me numerous errors, but the most recent is below:
The model item passed into the dictionary is of type
'System.Data.Entity.Infrastructure.DbQuery`1[MyApp.Models.AreaView]',
but this dictionary requires a model item of type
'MyApp.Models.AreaView'.
I understand that I am not passing the correct type for what the view is expecting, but I cannot seem to figure out:
Is the viewmodel setup correctly in the firstplace (how to mix values and a list of children
How to structure my linq query to get one AreaView object with
all my data
Pass it appropriately (in the correct type) to my
view
I have read about 45 posts on Stackoverflow, but can't seem to piece them together to accomplish what's above. If anyone has a correct solution (or even a direction), I would be very appreciative.
Thanks for any help.
I think you should add FirstOrDefault() at the end of your query to return the AreaView
public ActionResult List(int id = 0)
{
var model = (from f in areaDB.facility_list
where f.facility_id == id
select new AreaView
{
facility_id = f.facility_id,
facility_name = f.facility_name,
areas = (from a in areaDB.area_list
orderby a.area_name
where a.facility_id == id
select a).ToList()
}).FirstOrDefault();
return View(model);
}
I would not combine both object in the same query. I would do
1) Select AreaView where id = xxxx
2) Select Areas where id = xxxx
3) Assign areas to my AreaView
Example
AreaView model = GetAreaView(id);
model.Areas = GetAreas(id);
return View(model);
Also, try the following for your current code
return View(model.FirstOrDefault());
ASP.Net MVC 4
I am trying to populate a list of Countries (data from Country table in DB) in a dropdownlist. I get the following error:
The model item passed into the dictionary is of type
System.Collections.Generic.List`1[System.Int32]', but this dictionary requires a model item of type 'BIReport.Models.Country'.
I am new to ASP.Net MVC and I don't understand that error. What I feel is what Index method is returning doesn't match with the model that I am using in the View.
Model::
namespace BIReport.Models
{
public partial class Country
{
public int Country_ID { get; set; }
public string Country_Name { get; set; }
public string Country_Code { get; set; }
public string Country_Acronym { get; set; }
}
}
Controller::
public class HomeController : Controller
{
private CorpCostEntities _context;
public HomeController()
{
_context = new CorpCostEntities();
}
//
// GET: /Home/
public ActionResult Index()
{
var countries = _context.Countries.Select(arg => arg.Country_ID).ToList();
ViewData["Country_ID"] = new SelectList(countries);
return View(countries);
}
}
View::
#model BIReport.Models.Country
<label>
Country #Html.DropDownListFor(model => model.Country_ID, ViewData["Country_ID"] as SelectList)
</label>
Where am I going wrong?
You are selecting CountryIDs, therefore you will have a list of integers passed into the view.
I think you really want something like this:
public ActionResult Index()
{
var countries = _context.Countries.ToList();
ViewData["Country_ID"] = new SelectList(countries, "Country_ID", "Country_Name");
return View();
}
I'm not really sure why you have single country as a model for your view.
Update:
I'm still not sure why the model is a country, if you are just going to post the ID of the selected country you don't necessarily need a model at all (or just have an integer). This will be just fine though:
View
#model MvcApplication1.Models.Country
#Html.DropDownListFor(m => m.Country_ID, ViewData["Country_ID"] as SelectList)
the problem is in line 1 of your view. change it like this :
#model IEnumerable<BIReport.Models.Country>
also there is no need to pass the model to view if you already did it by :
ViewData["Country_ID"] = new SelectList(countries);
When you say #model BIReport.Models.Country it means your view is expecting a model consisting single country details. On the contrary you need a list of countries to be displayed in the drop-down list. Hence you should tell the view to look for a list of country details instead.
Therefore #model IEnumerable.