无法使用输入字段设置DateTime.始终返回DateTime.MinValue



我的程序应该有一个日期过滤器,并提供一篇具有正确日期的文章。但是当我在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参数相匹配。

你能试试吗?

最新更新