将HTML日期输入值添加到Ajax帖子中

时间:2019-06-10 00:07:23

标签: jquery html ajax datatables

我试图将两个日期输入添加到我可以从控制器访问的jquery数据表中。目标是按“发布日期”列过滤表。

我尝试将日期输入添加到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搜索。

1 个答案:

答案 0 :(得分:0)

为您的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;