在MVC中获取两个日期之间的数据

时间:2019-12-30 10:49:49

标签: asp.net-mvc

我需要帮助,当我选择明天的日期时,只有今天的数据。怎么处理呢?我没有设定任何日期。我在数据库中只有日期,而没有日期时间。

private static DataTable getData(string table, DateTime startDate, DateTime endDate)
    {
        string constr = ConfigurationManager.ConnectionStrings["db_Demo"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Table1 WHERE Entry_Datetime between '" + startDate + "' and '" + endDate + "'"))
            {
                using (SqlDataAdapter da = new SqlDataAdapter())
                {
                    DataTable dt = new DataTable();
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    da.SelectCommand = cmd;
                    da.Fill(dt);

                    return dt;
                }
            }
        }
    }

这是视图

<label for="startDate" style="color:mediumvioletred">From:</label>

            @Html.TextBox("startDate", DateTime.Today.ToString("yyyy-MM-dd"), new { @class = "form-control date", type = "date" })

        <label for="endDate" style="color:mediumvioletred">To:</label>

            @Html.TextBox("endDate", DateTime.Today.ToString("yyyy-MM-dd"), new { @class = "form-control date", type = "date" })


        <br />
        <input type="submit" class="btn btn-primary" value="Download" />
    }

1 个答案:

答案 0 :(得分:1)

我希望这能解决您的问题。

 string startDate = dtp_dfrom.Value.ToString("YYYY-MM-DD");
 string endDate = dtp_dto.Value.ToString("YYYY-MM-DD");       

 string constr = ConfigurationManager.ConnectionStrings["db_Demo"].ConnectionString;
 using (SqlConnection con = new SqlConnection(constr))
 {
  using (SqlCommand cmd = new SqlCommand("SELECT * FROM Table1 WHERE Entry_Datetime 
   between @startDate and @endDate"))
        {
  DataTable dt = new DataTable();
  cmd.Parameters.AddWithValue("@startDate", startDate);
  cmd.Parameters.AddWithValue("@endDate", endDate);
  cmd.CommandType = CommandType.Text;
  cmd.Connection = con;
  da.SelectCommand = cmd;
  da.Fill(dt);
  return dt;
}