嗨,当使用PagedList与ViewModel(与域模型完美配合)时,你真的需要你帮助解决问题。
我是MVC初学者,这是我到目前为止所尝试过的。
/ **********我有一个型号*********** /
public class Property
{
public int ID { get; set; }
public int UserID { get; set; }
public DateTime Created { get; set; }
public DateTime Edited { get; set; }
}
从中创建ViewModel(暂时只使用一个Domain模型从其他Domain模型添加更多属性
public class SearchResultsVM
{
public PagedList.IPagedList<Property> BasicDetails { get; set; }
}
控制器操作方法:
public ActionResult SearchResults(string sortOrder, string SearchKeyword, string currentFilter, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.TitleSortParm = String.IsNullOrEmpty(sortOrder) ? "title_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (SearchKeyword != null){page = 1;}
else{SearchKeyword = currentFilter;}
ViewBag.CurrentFilter = SearchKeyword;
var sr = from s in db.Property
select s;
if (!String.IsNullOrEmpty(SearchKeyword))
{sr = db.Property.Where(s => s.PropertyTitle.ToUpper().Contains(SearchKeyword.ToUpper()));}
switch (sortOrder)
{
case "title_desc":
sr = sr.OrderByDescending(s => s.PropertyTitle);
break;
case "Date":
sr = sr.OrderBy(s => s.Created);
break;
case "date_desc":
sr = sr.OrderByDescending(s => s.Created);
break;
default:
sr = sr.OrderBy(s => s.PropertyTitle);
break;
}
SearchResultsVM srVM = new SearchResultsVM();
int pageSize = 10;
int pageNumber = (page ?? 1);
srVM.BasicDetails = sr.ToList().ToPagedList(pageNumber,pageSize);
return View(srVM);
}
在View中访问ViewModel时我没有获得Property Domain Model的任何属性
@model PagedList.IPagedList<GH_Final.ViewModel.SearchResultsVM>
@using PagedList;
@using PagedList.Mvc;
@using (Html.BeginForm("SearchResults", "Home", FormMethod.Get))
{
<p>
Find by name: @Html.TextBox("SearchKeyword", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
</p>
}
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.created)
</td>
<td>
@Html.DisplayFor(modelItem => item.BasicDetails.Created)
</td>
<td>
@Html.DisplayFor(modelItem => item.BasicDetails.PropertyDesc)
</td>
答案 0 :(得分:2)
而不是:
@model PagedList.IPagedList<GH_Final.ViewModel.SearchResultsVM>
这样做:
@model GH_Final.ViewModel.SearchResultsVM
而不是:
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.created)
</td>
<td>
@Html.DisplayFor(modelItem => item.BasicDetails.Created)
</td>
<td>
@Html.DisplayFor(modelItem => item.BasicDetails.PropertyDesc)
</td>
应该是:
@foreach (var item in Model.BasicDetails)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Created)
</td>
<td>
@Html.DisplayFor(modelItem => item.Edited)
</td>
<td>
@Html.DisplayFor(modelItem => item.PropertyDesc)
</td>
<tr>
}
答案 1 :(得分:1)
您还应将表达式设为:
@Html.DisplayFor(modelItem => item.First().Created)
@Html.DisplayFor(modelItem => item.First().Edited)
@Html.DisplayFor(modelItem => item.First().PropertyDesc)