我知道还有其他类似的问题,但我无法在任何地方找到合适的解决方案。
关键是我希望用户在dropDownList中选择日期,将该日期作为操作方法的参数,并根据所选日期显示数据库的结果。但总是在dropDownList中选择任何项后,它会向控制器返回null。
这是我的控制器的方法:
public ActionResult Index(DateViewModel dateViewModel)
{
dateViewModel.Dates = GetDates();
return View(dateViewModel);
}
private IEnumerable<SelectListItem> GetDates()
{
var dbContext = new DbContext();
var dates = dbContext .TestResults
.Where(result => result.CompletedOn != null)
.OrderBy(result => result.CompletedOn)
.Select(result => result.CompletedOn).ToList();
var sortedDates = dates
.GroupBy(date => date.Month)
.Select(date => date.First())
.Select(date => new SelectListItem { Text = date.ToString("MMMM yy"), Value = date.Month.ToString() + " " + date.Year.ToString()})
.ToList();
return new SelectList(sortedDates, "Value", "Text");
}
[HttpPost]
public ActionResult ShowDepartmentArchive(string date)
{
//some logic with date here
return PartialView(depResults);
}
我有一个用于dropDownList的ViewModel:
public class DateViewModel
{
[Display(Name = "Выбранная дата")]
public string SelectedDate { get; set; }
[Display(Name = "Выберите дату: ")]
public IEnumerable<SelectListItem> Dates { get; set; }
}
最后,在我看来:
@model QA.Web.App.Models.DateViewModel
@using (Html.BeginForm("ShowDepartmentArchive", "Archive"))
{
@Html.Hidden("SelectedDate", Model.SelectedDate)
@Html.DropDownListFor(m => m.SelectedDate, Model.Dates, "Выберите
дату", new {onchange = "this.form.submit();"})}