【问题标题】:Cannot set DateTime with input field. Always returns DateTime.MinValue无法使用输入字段设置 DateTime。总是返回 DateTime.MinValue
【发布时间】:2019-11-03 17:05:24
【问题描述】:

我的程序应该有一个日期过滤器,并给出一个正确日期的文章。但是,当我在 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);
      }

【问题讨论】:

    标签: asp.net .net asp.net-mvc asp.net-core


    【解决方案1】:

    我认为您的问题是由命名不匹配引起的。

    在您看来,您正在声明一个名为 startdate 的文本框。 在您的控制器中,您期望它带有一个名为 startdateTime 的参数。

    结束日期同样不匹配。

    当您匹配这些名称时,参数绑定应该能够将输入值与控制器的 DateTime 参数匹配。

    你可以试试这个吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      相关资源
      最近更新 更多