我的程序应该具有日期过滤器,并为文章提供适当的日期。但是,当我在DateTime字段中输入任何日期时,我的值不会更改,并且始终为DateTime.MinValue。我不知道为什么以及如何解决它。
查看:
<form method="get">
<div class="form-inline form-group">
<label class="control-label"> since: </label>
@Html.TextBox("startdate", Model.StartDate, htmlAttributes: new { @class = "form-control" })
<label class="control-label"> till: </label>
@Html.TextBox("enddate", Model.EndDate, htmlAttributes: new { @class = "form-control" })
<input type="submit" value="Filtr" class="btn btn-default" />
</div>
</form>
型号:
public class MainView
{
public IEnumerable<Article> Articles { get; set; }
public string Name { get; set; }
public SelectList Categories { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public List<int> Tags { get; set; }
}
和控制器:
public IActionResult Index(int? category, string name, DateTime startdateTime, DateTime enddateTime)
{
IQueryable<Article> articles = db.Articles.Include(p => p.Category);
if (category != null && category != 0)
{
articles = articles.Where(p => p.CategoryId == category);
}
if (!String.IsNullOrEmpty(name))
{
articles = articles.Where(p => p.Name.Contains(name));
}
//if (startdateTime == null) startdateTime = DateTime.MinValue;
if (enddateTime ==DateTime.MinValue) enddateTime = DateTime.Now;
articles = articles.Where(p => p.Date>=startdateTime && p.Date <= enddateTime);
List<Category> categories = db.Categories.OrderBy(p=>p.Name).ToList();
categories.Insert(0, new Category { Name = "All", Id = 0 });
MainView viewModel = new MainView
{
Name = name,
StartDate = startdateTime,
EndDate = enddateTime
};
return View(viewModel);
}
我认为您的问题是由命名不匹配引起的。
在您看来,您正在声明一个名称为startdate
的文本框。在您的控制器中,您期望它带有一个名为startdateTime
的参数。
相同的不匹配项在结束日期。
当您匹配这些名称时,参数绑定应该能够使输入值与控制器的DateTime参数匹配。
您可以尝试一下吗?