将html日期输入值添加到ajax帖子

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (8)

我正在尝试将两个日期输入添加到我可以从我的控制器访问的jquery数据表中。目标是通过Date Released列过滤表。

我已经尝试将日期输入添加到cshtml页面并在.click函数中使用document.getElementById(“startDate”)。value,以便在用户单击搜索时设置输入值。但是当我尝试使用Request.Form在我的控制器中获取输入日期值时,该值为null。

index.cshtml

<div class="container-fluid">
    <div class="row">
        <div class="col-sm pull-left">
            <label>start: <input type="date" id = "startDate"/></label>
        </div>
        <div class="col-sm pull-left">
            <label>end: <input type="date" id = "endDate"/></label>
        </div>
    </div>
</div>

<body>
    <div class="row">
        <table id = "vehicles" class="table table-striped" cellspacing="0">
            <thead class="thin-border-bottom">
                <tr>
                    <th>Make</th>
                    <th>Model</th>
                    <th>Engine</th>
                    <th>Date Released</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                </tr>
            </tfoot>
        </table>
    </div>
</body>

vehicles.js

(function($) {
    var vehiclesTable = $("#vehicles")
        .dataTable({
            initComplete: function() {
                var input = $('.dataTables_filter input').unbind().attr('maxlength', 30),
                    self = this.api(),
                    $searchButton = $('<button class="btn btn-primary">')
                        .text('Search')
                        .click(function() {
                            var start = document.getElementById("startDate").value;
                            var end = document.getElementById("endDate").value;
                            self.search(input.val()).draw();
                        })

                $('.dataTables_filter').append($searchButton);
            },
            "searching": true,
            "processing": true,
            "serverSide": true,
            "responsive": true,
            "filter": true,
            "ajax": {
                "url": "/Vehicles/LoadVehicles",
                "method": "POST",
                "datatype": "json"
            },
            "columns": [
                {"data": "Make", "name": "Make", "autoWidth": true, "orderable": false},
                {"data": "Model", "name": "Model", "autoWidth": true, "orderable": false},
                {"data": "Engine", "name": "Engine", "autoWidth": true, "orderable": false},
                {"data": "DateReleased", "name": "DateReleased", "autoWidth": true, "orderable": false},
                {"data": "Price", "name": "Price", "autoWidth": true, "orderable": false},
            ],
            "ordering":false,
            "paging": true,
            "stateSave": false,
            "lengthMenu": [10, 25, 50, 100]
        });
})(jQuery);

VehiclesController.cs

public IActionResult LoadVehicles()
{
    string draw = HttpContext.Request.Form["draw"].FirstOrDefault();

    string start = Request.Form["start"].FirstOrDefault();

    string length = Request.Form["length"].FirstOrDefault();

    string sortColumn = Request.Form["columns[" + Request.Form["order[0]]"].FirstOrDefault() + "][name]"].FirstOrDefault();

    string searchValue = Request.Form["search[value]"].FirstOrDefault();

    string startDate = Request.Form["startDate"]; //null

    string endDate = Requst.Form["endDate"]; //null

    int pageSize = length != null ? Convert.ToInt32(length) : 0;
    int skip = start != null ? Convert.ToInt32(start) : 0;
    int recordsTotal = 0;

    List<Vehicle> VehicleData = new List<Vehicle>();
    VehicleData = objVehicle.GetVehicles(searchValue).ToList();

    recordsTotal = VehicleData.Count();

    var data = VehicleData.Skip(skip).Take(pageSize).ToList();

    return Json(new {draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data});

}

VehiclesDao.cs

public IEnumerable<Vehicle> GetVehicles(string searchValue) //add startDate and endDate
{
    List<Vehicle> lstVehicle = new List<Vehicle>();

    using (SqlConnection conn = new Sql Connection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("VehicleSearch"), conn);
        cmd.Parameters.AddWithValue("@SearchValue"), searchValue);
        //cmd.Parameters.AddWithValue("@StartDate"), startDate);
        //cmd.Parameters.AddWithValue("@EndDate"), endDate);
        cmd.CommandType = CommandType.StoredProcedure;
        conn.Open();
        SqlDataReader rdr = cmd.ExecuteReader();

        while (rdr.Read())
        {
            Vehicle Vehicles = new Vehicle();

            Vehicles.Make = rdr["Make"].ToString();
            Vehicles.Model = rdr["Model"].ToString();
            Vehicles.Engine = rdr["Engine"].ToString();
            Vehicles.DateReleased = rdr["DateReleased"].ToString();
            Vehicles.Price = rdr["Price"].ToString();

            lstVehicle.Add(Vehicles);
        }
    }

    return lstVehicle;
}

VehicleSearch存储过程

BEGIN   

SELECT 
    *
FROM
    [VehicleTable]
WHERE
    Make = @SearchValue
AND
    TRY_CAST(DateReleased AS DATE) >= @StartDate
AND 
    TRY_CAST(DateReleased AS DATE) <= @EndDate

END

我希望VehiclesController中的startDate和endDate变量设置为用户选择的任何日期,例如“07/09/2019”,但是当我选择两个日期,输入车辆制作并单击搜索时,仅填充searchValue。

提问于
用户回答回答于

为你的HTML

<div class="container-fluid">
<div class="row">
    <div class="col-sm pull-left">
        <label>start: <input type="date" id = "startDate" name="startDate"/></label>
    </div>
    <div class="col-sm pull-left">
        <label>end: <input type="date" id = "endDate" name="endDate"/></label>
    </div>
</div>

为你的ajax

"ajax": {
            "url": "/Vehicles/LoadVehicles",
            "method": "POST",
            "datatype": "json",
             data: function (d) {
                    d.startDate= $('input[name=startDate]').val();
                    d.endDate = $('input[name=endDate]').val();
                }
        }

在将其传递给查询之前,您可能还需要稍后进行日期转换

            double st = double.Parse(startdate);               
            double ed = double.Parse(enddate); 

            TimeSpan timest = TimeSpan.FromMilliseconds(st);
            TimeSpan timeed = TimeSpan.FromMilliseconds(ed);

            DateTime sdate = new DateTime(1970, 1, 1).AddHours(1) + timest;
            DateTime edate = new DateTime(1970, 1, 1) + timeed;

扫码关注云+社区

领取腾讯云代金券