Reputation: 780
I have a View
that needs to display, for example, a User
and a Role
table. I need to create 2 LINQ
queries to be returned in the View, one for the User
and the other one for the Role
so that I can display 2 tables in the view. So far, I can only return the User
, but how do I return also the Role
? Here's my current setup:
UserModel
-The ViewModel
is being used in View's textboxes and the Model
for the looping of records in the table
public class UserModel
{
public int user_id { get; set; }
public string user_name { get; set; }
...
}
UserViewModel
public class UserViewModel
{
public IPagedList<CDS.Models.UserModel> Users { set; get; }
public int userId { get; set; }
public string userName { get; set; }
...
}
View
@model CDS.Models.UserViewModel
@using PagedList.Mvc;
@using (Html.BeginForm("Create", "User", FormMethod.Get))
{
@Html.HiddenFor(m => m.userId)
@Html.LabelFor(m => m.userName)
@Html.TextBoxFor(m => m.userName)
<table id="dbTable">
<thead>
<tr>
<th class="hidden">
@Html.DisplayNameFor(model => model.user_id)
</th>
<th>
@Html.ActionLink("User", "Create", new { sortOrder = ViewBag.UserSort, currentFilter = ViewBag.CurrentFilter })
</th>
</tr>
</thead>
<tbody id="dbBody">
@foreach (var item in Model.Users)
{
<tr>
<td class="hidden">
@Html.DisplayFor(modelItem => item.user_id)
</td>
<td>
@Html.DisplayFor(modelItem => item.user_name)
</td>
</tr>
}
</tbody>
</table>
//Don't mind this code, it's only for the pagination
Page @(Model.Users.PageCount < Model.Users.PageNumber ? 0 : Model.Users.PageNumber) of @Model.Users.PageCount
@Html.PagedListPager(Model.Users, page => Url.Action("Create",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
}
UserController - How can I return a ViewModel
with another LINQ
for the Role?
DBEntities _odb = new DBEntities();
public ActionResult Create(string sortOrder, string currentFilter, string searchString, int? page)
{
var user = from u in _odb.USR_MSTR
select new UserModel
{
user_id = u.USR_ID,
user_name = u.USR_NAME,
};
int pageSize = 10;
int pageNumber = (page ?? 1);
var vm = new UserViewModel();
vm.Users = user.ToPagedList(pageNumber, pageSize);
return View(vm);
}
Upvotes: 1
Views: 145
Reputation:
Two options you can consider.
Add an additional property in you view model for the collection of Role
public IEnumerable<Role> Roles { get; set; }
and in the GET method
var roles = db.Roles..... // your query
var vm = new UserViewModel()
{
Roles = roles,
Users = user.ToPagedList(pageNumber, pageSize)
};
return View(vm);
Or create a ChildActionOnly method that returns a partial view of your roles
[ChildActionOnly]
public ActionResult FetchRoles()
{
var model = ... // your query
return PartialView(model);
}
and in FetchRoles.cshtml
@model IEnumerable<Role>
... // html to display roles
then in the main view, render it using
@{ Html.RenderAction("FetchRoles", "yourControllerName"); }
Upvotes: 1