我正在创建我的第一个基于MVC示例的示例应用程序。
我有一个模特: -
public class SampleClass
{
public int ID { get; set; }
[Required]
public string Description { get; set; }
[Range(1,100)]
public int Age { get; set; }
[Display(Name="Created On")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CreatedDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? LastUpdated { get; set; }
public string itemGenre { get; set; }
}
一个Index.cshtml页面,显示: -
<p>
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm("Index", "Sample", FormMethod.Get))
{
<p style="margin-bottom:30px;">
<div style="display:inline-block; float:left; border:1px dotted black; padding:20px;">
Created Date: @Html.TextBox("fromDate")
<input type="submit" value="Filter" />
</div>
<div style="display: inline-block; border: 1px dotted black; padding: 20px; margin-left:170px;">
Genre: @Html.DropDownList("itemGenre", "All")
</div>
<div style="display: inline-block; float: right; border: 1px dotted black; padding: 20px;">
Search: @Html.TextBox("searchString")
<input type="submit" value="Filter" />
</div>
</p>
}
</p>
我已经让CreatedDate和SearchString的过滤方法正常工作了。但我似乎无法让我的DropDown菜单过滤器“itemGenre”正常工作。虽然我的下拉菜单填充了我的数据库中存储的正确值/字符串,但每次进行回发时,我的控制器类中的itemGenre都会被检索为空值: -
public ActionResult Index(DateTime? fromDate, string itemGenere, string searchString)
{
var GenreList = new List<string>();
var GenreQuery = from d in db.Sample
orderby d.itemGenre
select d.itemGenre;
GenreList.AddRange(GenreQuery.Distinct());
ViewBag.itemGenre = new SelectList(GenreList);
var items = from i in db.Sample
select i;
if (!String.IsNullOrEmpty(searchString))
{
items = items.Where(o => o.Description.Contains(searchString));
}
if (!String.IsNullOrEmpty(Convert.ToString(fromDate)))
{
items = items.Where(p => p.CreatedDate >= fromDate);
}
if(!String.IsNullOrEmpty(itemGenere))
{
items = items.Where(q => q.itemGenre == itemGenere);
}
return View(items);
}
我想知道我哪里出错了?