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>
}
}
Related
I have two models and I need to display data in my layout page and in every page that the user visit. Those two models have not any relationship between them so I don't need any join.
this is my controller
public ActionResult Index()
{
var notification = (from n in db.Notification
where n.NotificationIsSeen == true
select n);
var task = (from t in db.Task
where t.TaskIsSeen == true
select t);
return View();// I not sure how to return both of queries
}
I also create a model that contains both of them but I 'not sure if this is the right way
public class Layout
{
public Notification Notification { get; set; }
public Task Task { get; set; }
}
and in my layout page
#model IEnumerable<MyprojectName.Models.Layout>
//other code
#foreach (var item in Model)
{
<li>#Html.DisplayFor(modelItem => item.Notification.NotificationSubject ) </li>}
//other code
#foreach (var item in Model)
{
<li>#Html.DisplayFor(modelItem => item.Task.TaskSubject )
</li>
}
I have seen other similar question but they work with join tables.
I need some help on returning data of both tables. thank you in advance
Your queries in your action method both return collections of data. To accommodate this your view model needs to have two lists and needs to look something like this. You have to be able to store these collections in lists when sending them to the view:
public class Layout
{
public IEnumerable<Notification> Notifications { get; set; }
public IEnumerable<Task> Tasks { get; set; }
}
To populate these lists change the code in your action method to this. Create an instance of Layout, populate the two lists and then send the instance to the view:
public ActionResult Index()
{
Layout model = new Layout();
model.Notifications = (from n in db.Notification
where n.NotificationIsSeen == true
select n);
model.Tasks = (from t in db.Task
where t.TaskIsSeen == true
select t);
return View(model);
}
Your view needs to accept and instance of Layout:
#model MyprojectName.Models.Layout
#foreach (var notification in Model.Notifications)
{
<div>
#notification.NotificationSubject
</div>
}
#foreach (var task in Model.Tasks)
{
<div>
#task.TaskSubject
</div>
}
I hope this helps.
Please declare list type of model in you layout model
Layout Model
public class Layout
{
public IEnumerable<Notification> Notifications { get; set; }
public IEnumerable<Task> Tasks { get; set; }
}
Controller
public ActionResult Index()
{
Layout model = new Layout();
model.Notifications = (from n in db.Notification
where n.NotificationIsSeen == true
select n);
model.Tasks = (from t in db.Task
where t.TaskIsSeen == true
select t);
return View(model);
}
View
#model MyprojectName.Models.Layout
#foreach(var item in Model.Notifications)
{
// access your item.propertyname
}
#foreach(var item in Model.Task)
{
// access your item.propertyname
}
Using partial view for build the dynamic header
1 - create action with partial view and display data
2 - go to layout to call this
#Html.partial("Action","Controller")
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>
I am fairly new to MVC, and I've been reading a bit about ViewModels, but how do I go about sending two models to my View, where the queries are like so
public ActionResult Index(int Id)
{
var People = from a in db.Person
select a;
var Data = from a in db.Member
where a.Person.PersonId.Equals(Id)
select new
{
a.Project.ProjectId,
a.Project.Name,
a.Project.Customer,
a.Project.TechProfile.Select(x => new
{
x.TechId,
x.Name,
x.Elements
}),
a.MemberId,
a.Role,
a.Start,
a.End
};
return View(People);
}
I was using #model IQueryable<GeoCV.Models.Person> before so I could use a #foreach in my View but I don't know how to get my other query to the View so I can get data from it too.
Update
And I'm making a custom class for my Data query, but I don't know how to set the property of TechProfile
Right now I have
public IEnumerable<TechProfile> ProjectTechProfile { get; set; }
In my custom class, but it doesn't work, so I guess I have to specify TechId, Name and Elements?
But how?
A ViewModel wraps around the 2 models you are getting with your 2 queries, so you can return it as a single object to your view. In your case we need to adress another issue first. You are returning an anonymous object in your data query.
This means, your data query needs to return a strongly typed object instead of an anonymous object.
Create a class for your data query:
public class MyCustomDataObject
{
public int ProjectId { get; set; }
//... map all properties as needed
}
then edit your data query to return this object:
var Data = from a in db.Member
where a.Person.PersonId.Equals(Id)
select new MyCustomDataObject
{
ProjectId = a.Project.ProjectId,
//assign all properties
};
Now you need to create the actual ViewModel class:
public class MyViewModel
{
public IEnumerable<Person> Persons { get; set; }
public IEnumerable<MyCustomDataObject> Data { get; set; }
}
And after this you just need to assign the values to it in your Actionmethod:
public ActionResult Index(int Id)
{
var People = from a in db.Person
select a;
var Data = from a in db.Member
where a.Person.PersonId.Equals(Id)
select new MyCustomDataObject
{
ProjectId = a.Project.ProjectId,
//...
};
//store data of both queries in your ViewModel class here:
var vm = new MyCustomDataObject();
vm.Persons = People;
vm.Data = Data
//return ViewModel to View.
return View(vm);
}
And then declare it in your view: #model Namespace.Subfolder.MyCustomDataObject
You can use #Html.Action("actionName","controllerName") method in view. You can divide your original view into multiple partial view and then you can render that partial view with dynamic model binding using #Html.Action("actionName","controllerName") method.
For more details with sample code http://devproconnections.com/development/how-use-aspnet-mvc-render-action-helpers
You can have methods like below to get multiple model in single view
private IList<People> GetPeople()
{
return from a in db.Person
select a;
}
private IList<Data> GetData()
{
return from a in db.Member
where a.Person.PersonId.Equals(Id)
select new
{
a.Project.ProjectId,
a.Project.Name,
a.Project.Customer,
a.Project.TechProfile.Select(x => new
{
x.TechId,
x.Name,
x.Elements
}),
a.MemberId,
a.Role,
a.Start,
a.End
};
}
public ActionResult Index(int Id)
{
var MultipleModel = new Tuple<IList<People>,IList<Data>>(GetPeople(),GetData()) { };
return View(MultipleModel);
}
Here's a codeproject tutorial on the subject.
I have a problem, I have the next controller
namespace RolesMVC3.Areas.Administrador.Controllers
{
[Authorize(Roles = "Adminr")]
public class HomeController : Controller
{
private BASEDATOSCJ_2Entities db = new BASEDATOSCJ_2Entities();
public ActionResult Index()
{
string username = User.Identity.Name;
MembershipUser user = Membership.GetUser(username);
Guid key = (Guid)Membership.GetUser().ProviderUserKey;
var Universities = (from u in db.UNIVERSITy
join s in db.CAMPUS_UNIVERSITy on u.IdUniversity equals s.IdUniversity
join c in db.CIUDAD_CAMPUS on s.IdCiudadSede equals c.IdCiudadSede
join co in db.OFFICE on s.Idoffice equals co.Idoffice
join uxc in db.USERxOFFICE on co.Idoffice equals uxc.Idoffice
where uxc.UserId == key
select new { u.Name, namecity = c.Nombre, s.Idoffice}).ToList();
return View(Universities);
}
With this controller I just want send to View u.Name, and s.Idoffice. How I do? (in fact do not know if this controllet is fine), I want to send fields belong to different tables. I want to send the query as a list and present at the View, ViewBag go with it?, How do I pass these data to the view and display with a foreach?.
I use razor
If you change the following line:
select new { u.Name, namecity = c.Nombre, s.Idoffice}
To
select new { Name = u.Name, Idoffice = s.Idoffice }
This only selects the two fields into a list. In your view you can do the following:
#model List<dynamic>
#foreach(dynamic d in Model) {
<p>#d.Name</p>
<p>#d.Idoffice</p>
}
Edit:
You might want to define a ViewModel to contain your data.
public class MyViewModel {
string Name {get;set;}
string Idoffice {get;set;}
}
Now you can change your select statement as follows:
select new MyViewModel { Name = u.Name, Idoffice = s.Idoffice }
And update your Razor file as such:
#model List<MyViewModel>
#foreach(MyViewModel d in Model) {
<p>#d.Name</p>
<p>#d.Idoffice</p>
}
I would use a view model. I have learnt not to expose my domain objects to the view, I rather map my domain object to the view model and return this view model to the view.
Separate you data access logic from your view logic. You can put that whole statement into a repository class and then you just call this method from the controller.
Here is a partial view model, you might have more properties if you need more data to be displayed:
public class UniversityViewModel
{
IEnumerable<University> Universities { get; set; }
}
University class:
public class University
{
public string Name { get; set; }
public string Idoffice { get; set; }
}
In my action method of my controller it would look something like this:
public ActionResult Index(int id)
{
UniversityViewModel viewModel = new UniversityViewModel
{
Universities = universityRepository.GetAll()
};
return View(viewModel);
}
And in my view I would have the following:
<table>
#foreach(University university in Model.Universities)
{
<tr>
<td>Name:</td>
<td>university.Name</td>
</tr>
}
</table>
This is just a basic display of data in the view, you can use 3rd party components to display your data with some features.
I'm kind of new to razor MVC, and I'm wondering how can I read the values I return in the view?
My code is like this:
public ActionResult Subject(int Category)
{
var db = new KnowledgeDBEntities();
var category = db.categories.Single(c => c.category_id == Category).name;
var items = from i in db.category_items
where i.category_id == Category
select new { ID = i.category_id, Name = i.name };
var entries = from e in db.item_entry
where items.Any(item => item.ID == e.category_item_id)
select new { ID = e.category_item_id, e.title };
db.Dispose();
var model = new { Name = category, Items = items, Entries = entries };
return View(model);
}
Basically, I return an anonymous type, what code do I have to write to read the values of the anonymous type in my view?
And if this is not possible, what would be the appropriate alternative?
Basically, I return an anonymous type
Nope. Ain't gonna work. Anonymous types are emitted as internal by the compiler and since ASP.NET compiles your views into separate assemblies at runtime they cannot access those anonymous types which live in the assembly that has defined them.
In a properly designed ASP.NET MVC application you work with view models. So you start by defining some:
public class MyViewModel
{
public string CategoryName { get; set; }
public IEnumerable<ItemViewModel> Items { get; set; }
public IEnumerable<EntryViewModel> Entries { get; set; }
}
public class ItemViewModel
{
public int ID { get; set; }
public string Name { get; set; }
}
public class EntryViewModel
{
public int ID { get; set; }
public string Title { get; set; }
}
and then you adapt your controller action to pass this view model to the view:
public ActionResult Subject(int Category)
{
using (var db = new KnowledgeDBEntities())
{
var category = db.categories.Single(c => c.category_id == Category).name;
var items =
from i in db.category_items
where i.category_id == Category
select new ItemViewModel
{
ID = i.category_id,
Name = i.name
};
var entries =
from e in db.item_entry
where items.Any(item => item.ID == e.category_item_id)
select new EntryViewModel
{
ID = e.category_item_id,
Title = e.title
};
var model = new MyViewModel
{
CategoryName = category,
Items = items.ToList(), // be eager
Entries = entries.ToList() // be eager
};
return View(model);
}
}
and finally you strongly type your view to the view model you have defined:
#model MyViewModel
#Model.Name
<h2>Items:</h2>
#foreach (var item in Model.Items)
{
<div>#item.Name</div>
}
<h2>Entries:</h2>
#foreach (var entry in Model.Entries)
{
<div>#entry.Title</div>
}
By the way to ease the mapping between your domain models and view models I would recommend you checking out AutoMapper.
Oh, and since writing foreach loops in a view is kinda ugly and not reusable I would recommend you using display/editor templates which would basically make you view look like this:
#model MyViewModel
#Model.Name
<h2>Items:</h2>
#Html.DisplayFor(x => x.Items)
<h2>Entries:</h2>
#Html.DisplayFor(x => x.Entries)
and then you would define the respective display templates which will be automatically rendered for each element of the respective collections:
~/Views/Shared/DisplayTemplates/ItemViewModel:
#model ItemViewModel
<div>#item.Name</div>
and ~/Views/Shared/DisplayTemplates/EntryViewModel:
#model EntryViewModel
<div>#item.Title</div>