我已经读到使用 ViewBags 通常是一种不好的做法,并且混合 ViewBag 和 ViewModels 也不好,但是我使用一些 ViewBagssort order
在我的控制器和视图之间传递参数,尽管我可以在ViewModel
视图上创建属性我在我首先创建模型之前需要这些值,所以看不到如何解决这个问题。
控制器
public ActionResult Index(string sortOrder, string searchString,
string currentFilter, int? page,
bool? includeComplete)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParam = string.IsNullOrWhiteSpace(sortOrder) ? "Name desc" : "";
ViewBag.DateSortParam = sortOrder == "Date" ? "Date desc" : "Date";
if (Request.HttpMethod == "GET")
searchString = currentFilter;
else
page = 1;
ViewBag.CurrentFilter = searchString;
bool showCompleted = (includeComplete == null || includeComplete == false)
? false : true;
ViewBag.IncludeCompleted = showCompleted;
int pageNumber = (page ?? 1);
var query = Session.QueryOver<ToDo>();
if (!string.IsNullOrWhiteSpace(searchString))
query = query.WhereRestrictionOn(td => td.TaskName)
.IsInsensitiveLike(string.Format("%{0}%", searchString));
if (!showCompleted)
query.And(td => td.IsComplete == false);
switch (sortOrder)
{
case "Name desc":
query = query.OrderBy(td => td.TaskName).Desc;
break;
case "Date":
query = query.OrderBy(td => td.DueDate).Asc;
break;
case "Date desc":
query = query.OrderBy(td => td.DueDate).Desc;
break;
default:
query = query.OrderBy(td => td.TaskName).Asc;
break;
}
var result = query.Fetch(p=>p.Priority).Eager
.Fetch(s=>s.Staff).Eager
.List();
var viewModel = AutoMapper.Mapper.Map<IEnumerable<ToDo>,
IEnumerable<IndexToDoViewModel>>(result)
.ToPagedList(pageNumber, PageSize);
return View(viewModel);
}
然后在我看来,我将使用 ViewBag 将值传递回控制器,例如sortOrder
在我可以将其应用到构成方法主体的查询中之前我需要拥有的值NHibernate
,例如:
@Html.ActionLink("Name", "Index", new {sortOrder=ViewBag.NameSortParam,
includeComplete = ViewBag.IncludeCompleted})
我的视图模型
public class IndexToDoViewModel
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
[DisplayName("Date Due")]
public DateTime? DueDate { get; set; }
public Guid Id { get; set; }
[DisplayName("Is Complete")]
public bool IsComplete { get; set; }
[DataType(DataType.MultilineText)]
public String Notes { get; set; }
public string Priority { get; set; }
public string Staff {get; set;}
[DisplayName("Name")]
public String TaskName { get; set; }
// These would potentially replace my ViewBag?
public string CurrentSort { get; set; }
public string CurrentFilter { get; set; }
public string NameSortParam { get; set; }
public string DateSortParam { get; set; }
public bool IncludeCompleted { get; set; }
}