Display data for two tables to layout page MVC 5 - asp.net-mvc

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")

Related

how to show multi level tables in mvc?

I'm new in mvc . i have this diagram part of my data base diagram
I want to show to orders user , status order and products order.and i test many ways but not successful.
in view model:
public class OrderListViewModel
{
public List<Order> orders { get; set; }
}
controller:
BOL.User CurrentUser = _user.user.GetUser(User.Identity.Name);
int UserId = CurrentUser.ID;
var listorders = _order.UserOrders(UserId) ;
List<OrderListViewModel> orderVM = new List<OrderListViewModel>();
orderVM.Add (new OrderListViewModel { orders=listorders.ToList()
}
);
return View(orderVM);
in view:
#model IEnumerable<OrderListViewModel>
#foreach (var item in Model)
{
Html.Display(item.orders.Select(x=>x.Status.StatusName).FirstOrDefault());
foreach (var fact in item.orders.ToList())
{
Html.Display(fact.Factors.);
}
<br />
Html.Display("****");
}
and i don't know how to show products in each order??

How to implement GroupBy using linq in razor view

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>
}
}

.NET MVC - 2 foreach loops

My code goes like this;
First Loop
#foreach (var item in Model)
{
if (item.IsValid && item.IsRecommended)
{
and the second one
#foreach (var item in Model)
{
if (item.IsValid && !item.IsRecommended)
{
I am using "#using PagedList; #using PagedList.Mvc;"
i want my page to display recommended products first and than the rest of the products. There is 15 products/page and 150 products in total.
Best regards,
Try This One
In Your Model Create Two Classes For RecommendedProduct.cs and RestOfProducts.cs
Create new Model Class
public class Products
{
public List<RecommendedProduct> RecommenedProd { get; set; }
public List<RestOfProducts> RestProd { get; set; }
}
In Controller
public ActionResult Create()
{
Products Obj = new Products();
Obj.RecommenedProd = Your recommend product ;//Your Recommended Product List
Obj.RestProd = Your recommend product ;//Your rest of product List
return View(Obj);
}
View
#model Products
#foreach (var item in Model.RecommenedProd )
{
// Do Something
}
#foreach (var item in Model.RestProd )
{
// Do Something
}

Display List in View in MVC

I have a List with has three values.I want to display in view.Here is my approach
My Controller Function
public List<Movie> Index()
{
Movie obj = new Movie();
return obj.ShowData();
}
My model class & Function
Database db = DatabaseFactory.CreateDatabase("MyDBLINK");
public int ID { get; set; }
public string Title { get; set; }
public List<Movie> GetData()
{
try
{
DbCommand dbCommand = db.GetStoredProcCommand("SP");
DataSet dsResult = db.ExecuteDataSet(dbCommand);
List<Movie> Prop = new System.Collections.Generic.List<Movie>();
Prop = (from DataRow row in dsResult.Tables[0].Rows
select new Movie
{
ID = Convert.ToInt32(row["ID"].ToString()),
Title = row["Title"].ToString()
}).ToList();
return Prop;
}
catch (Exception ex)
{
return null;
}
}
Here is my view
#model System.Collections.Generic.List<MvcFirst.Controllers.MoviesController>
#foreach (var item in Model)
{
<ul>
<li>#item.ID</li>
<li>#item.Title</li>
</ul>
}
My Question is how to display this list in View?
Secondly Is this approach is Good for CPU?
Everything looks almost fine, your controller should be something like this:
public ActionResult Index()
{
var movie = new Movie();
var result = movie.GetData(); // instance object and read the method to get the list
return View(result);
}
An ActionResult could be any type of result, a View, a File to download, a Javascript, A StyleSheet, etc... but normaly is a View with the same name of action. If your action method is called Index, asp.net mvc will search for a View called Index on the Views folder. The part return View(result); means you are returning this View and passing the result object as a Model to your View.
Your View should be strogly typed with the entity (because you are returning it from the controller), not the controller:
#model System.Collections.Generic.List<Movie>
#foreach (var item in Model)
{
<ul>
<li>#item.ID</li>
<li>#item.Title</li>
</ul>
}
I think you've missunderstood how Controllers and Views work. Your Index() method need to return an ActionResult which will generate your view and return it to the user.
//My Controller Function
public ActionResult Index()
{
Movie obj = new Movie();
return View(obj.GetData()); //This will take the view with the same name as your method (Index in this case) and return it to the client/browser.
}
I hope I understood you question correctly.
Edit: I forgot to make the view stronly typed as Felipe Oriani has showned you

Displaying one object value (from a collection) in a label

I am learning MVC4. I could display records in a tabular format using foreach.
Now, I need to display theDescription of (only) first Topic object in a label. I need to do it without a foreach. How can we do it?
VIEW
#model MvcSampleApplication.Models.LabelDisplay
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
foreach (var item in Model.Topics.Select((model, index) => new { index, model }))
{
<div>#(item.index) --- #item.model.Description---- #item.model.Code</div> <div></div>
}
}
Controller Action
public ActionResult Index()
{
LabelDisplay model = new LabelDisplay();
Topic t = new Topic();
t.Description = "Computer";
t.Code=101;
Topic t3 = new Topic();
t3.Description = "Electrical";
t3.Code = 102;
model.Topics = new List<Topic>();
model.Topics.Add(t);
model.Topics.Add(t3);
return View(model);
}
Model
namespace MvcSampleApplication.Models
{
public class LabelDisplay
{
public List<Topic> Topics;
}
public class Topic
{
public string Description { get; set; }
public int Code { get; set; }
}
}
REFERENCE
Iterate through collection and print Index and Item in Razor
I need to display theDescription of (only) first Topic object in a label
Unless I totally misunderstood you, selecting the first item (only) in your view would look something like:
#if (Model.Topics.Any())
{
#Html.DisplayFor(x => x.Topics.First().Description)
}

Resources