1

我有一个剑道下拉列表它可以工作,但我需要让它成为一个没有按钮的实时下拉列表......每当我在下拉列表中选择一个项目时,它会自动更新我的网格内的内容或我的网格上的查询基于选择的下拉列表。

这是我的代码:

@using (Html.BeginForm())
{
    <input type="hidden" id="hiddenUser" name="hiddenUser" value="@userId" />
    <p>
        <input id="ddlWorker" name="ddlWorker" style="width: 250px;"   value="@ddlWorker" />
        &nbsp;
        <input type="submit" value="Filter Workers by Position" class="styledButton" />
    </p>
}

JS:

var userId = $("#hiddenUser").val();

$("#ddlWorker").kendoDropDownList({
    dataTextField: "JobCode",
    dataValueField: "ID",
    autoBind: false,

    optionLabel: {
        JobCode: "--- Please Select Position ---",
        ID: ""
    },
    // define custom template
    template: '<h5>${ data.JobCode }</h5>',

    dataSource: {
        transport: {
            read: {
                url: '/Worker/LoadWorkerDropdownList?userId=' + userId,
                dataType: "json",
                type: "POST"
            }
        }
    }
});

var dropdownlist = $("#ddlWorker").data("kendoDropDownList");

dropdownlist.list.width(250);

我的网格控制器

public JsonResult LoadWorkerList( string search, int? positionSelected, int? statusValue)
        {


            // check if search string has value
            // retrieve list of workers filtered by search criteria
            var list = (from a in db.Workers
                        where a.LogicalDelete == false
                        select a).ToList();

            List<WorkerInfo> wlist = new List<WorkerInfo>();
            foreach (var row in list)
            {
                WorkerInfo ci = new WorkerInfo
                {
                    ID = row.ID,
                    FirstName = row.FirstName,
                    LastName = row.LastName,
                    Name = row.FirstName + " " + row.LastName,
                    LastFName = row.LastName + " " + row.FirstName,
                    PositionSelected = positionSelected,
                    LogicalDelete = row.LogicalDelete

                };
                wlist.Add(ci);
            }
            if (positionSelected.HasValue)
            {
                var workerIdList = new List<Int32>();

                var filterList = (from a in db.Client_Worker_Position
                                  where a.LogicalDelete == false && positionSelected == a.ClientCustomerPositionID
                                  select a).ToList();
                var listSelect = (from a in db.Worker_Availability
                                  where a.LogicalDelete == false
                                  select a).ToList();

                foreach (var row in listSelect)
                {

                    var shiftList = (from a in db.Client_Customer_Position_Shift
                                     where a.LogicalDelete == false && positionSelected == a.Client_Customer_PositionID
                                     select a).ToList();

                    foreach (var positionShift in shiftList)
                    {


                        if (positionShift.Day_LookID == row.AvailableDay_LookID || positionShift.Day_LookID == 76 || row.AvailableDay_LookID == 76)
                        {

                            if (((positionShift.StartTime == "Anytime" && positionShift.EndTime == "Anytime") || (row.StartTime == "Anytime" && row.EndTime == "Anytime")) ||
                                 (row.StartTime == "Anytime" || row.EndTime == "Anytime") || (positionShift.StartTime == "Anytime" || positionShift.EndTime == "Anytime"))
                            {
                                workerIdList.Add(row.ID);
                            }
                            else
                            {
                                DateTime posStartTime = Convert.ToDateTime(positionShift.StartTime);
                                DateTime availStartTime = Convert.ToDateTime(row.StartTime);
                                DateTime posEndTime = Convert.ToDateTime(positionShift.EndTime);
                                DateTime availEndTime = Convert.ToDateTime(row.EndTime);


                                if ((positionShift.StartTime == row.StartTime &&
                                    positionShift.EndTime == row.EndTime) || (positionShift.StartTime == row.StartTime ||
                                    positionShift.EndTime == row.EndTime)
                                    || (posStartTime < availStartTime && posEndTime > availEndTime))
                                {
                                    workerIdList.Add(row.ID);
                                }
                            }

                        }

                    }

                }

                var toBeList = (from a in listSelect

                                where a.LogicalDelete == false
                                select a).ToList();
                var setToList = toBeList.Select(x => x.ID).Except(filterList.Select(y => y.WorkerAvailabilityId)).ToList();

                var selectedPosition = (from a in listSelect
                                        join b in db.Workers
                                        on a.Worker_ID equals b.ID
                                        join c in db.Client_Customer_Position
                                        on positionSelected equals c.ID
                                        where workerIdList.Contains(a.ID) && a.LogicalDelete == false && b.LogicalDelete == false
                                        && c.LogicalDelete == false && setToList.Contains(a.ID)
                                        select new WorkerInfo()
                                        {
                                            ID = b.ID,
                                            WorkerAvailID = a.ID,
                                            FirstName = b.FirstName,
                                            PositionSelected = positionSelected,
                                            LastName = b.LastName


                                        }).ToList();


                var distinctList = selectedPosition.GroupBy(x => x.ID)
                         .Select(g => g.First())
                         .ToList();


                wlist = distinctList.ToList();

            }
            if (!search.Equals("Search Worker"))
            {

                var wolist = (from a in wlist
                              where a.FirstName.ToLower().Contains(search.ToLower()) ||
                              a.LastName.ToLower().Equals(search.ToLower()) ||
                              a.Name.ToLower().Equals(search.ToLower()) ||
                              a.LastFName.ToLower().Equals(search.ToLower())
                              select a).ToList();
                wlist = wolist;
            }
            else
            {
                var wolist = (from a in wlist
                              where a.LogicalDelete == false
                              select a).ToList();
                wlist = wolist;
            }
            ViewBag.positionSelected = positionSelected;
            return Json(wlist.ToList().OrderBy(p => p.FirstName.ToLower()), JsonRequestBehavior.AllowGet);
        }

感谢:D

4

2 回答 2

1

据我了解,您想在 Kendo Dropdownlist 中选择一个值,并且应该根据选择更新 Kendo Grid 中的数据。

首先,在下拉列表中,您应该与事件绑定,该事件最终会在服务器端发出请求并将其保存在会话或其他内容中。

$("#ddlWorker").kendoDropDownList({
                    dataTextField: "JobCode",
                    dataValueField: "ID",
                    autoBind: false,

                    select: onDDLSelect,

                    optionLabel: {
                        JobCode: "--- Please Select Position ---",
                        ID: ""    
                    },

                    // define custom template
                    template: '<h5>${ data.JobCode }</h5>',

                    dataSource: {
                        transport: {
                            read: {
                                url: '/Worker/LoadWorkerDropdownList?userId=' + userId,
                                dataType: "json",
                                type: "POST"    
                            }
                        }
                    }        
                });

现在您对服务器端进行简单的 JSon 调用,如下所示

function onDDLSelect() {

    var statusValue = $("#ddlWorker").val();

    $.ajax({
        url: '/Worker/ddlWorkerChanged',
        type: "POST",
        data: { "statusValue": statusValue },
        dataType: "json"
    }).done(delayedRefresh());
}

delayRefresh() 的主要原因是在我们调用剑道网格重新加载之前给 JSon 一些时间来完成它的工作。您可以进行同步 ajax 调用来删除它。

function delayedRefresh() {
    window.setTimeout(Refresh, 500);
}

function Refresh() {        
    $("#YourGridName").data("kendoGrid").dataSource.read();
}

现在在服务器端,您可以通过某种方式读取 onDDLSelect() 为剑道网格保存的值。一些检查,例如您的下拉值是否存在。如果存在,则查询所选值,否则查询所有值。

[HttpPost] 
public void ddlWorkerChanged(string statusValue) 
{ 
// you save the ddl selection in session or the way you prefer 
} 

您保存它并在几秒钟后返回。

$("#YourGridName").data("kendoGrid").dataSource.read(); 

它将触发并告诉您的网格再次重新加载其数据。假设以下是您在服务器端的 Kendo Grid 读取功能(比如说它在 GetShiftReportData 上命中)..

public ActionResult GetShiftReportData([DataSourceRequest]DataSourceRequest request) 
{ 
  //if (session data is present) 
    //{ selected query } 
  //else 
    //{ regular query } 

  return Json(result, JsonRequestBehavior.AllowGet); 
}

更多参考见剑道官方演示@http ://demos.kendoui.c​​om/web/dropdownlist/ events.html

于 2014-01-16T07:04:26.703 回答
1

这是 Kendo DropDownList 的工作副本,它将更改 Kendo Grid 的值。

我的 HTML:我已经为 kendo 和通用标记链接了必要的 css/js 文件来挂钩 kendo 控件。

<link href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.rtl.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.silver.min.css" rel="stylesheet" />

<script src="@Url.Content("http://cdn.kendostatic.com/2013.3.1119/js/jquery.min.js")"></script>
<script src="@Url.Content("http://cdn.kendostatic.com/2013.3.1119/js/kendo.all.min.js")"></script>
<script src="@Url.Content("http://cdn.kendostatic.com/2013.3.1119/js/kendo.aspnetmvc.min.js")"></script>

<div>
    <label class="control-label" for="shiftName">Shift</label>
    <div class="controls">
        <input id="ShiftInputs" type="text" style="width: 100%; min-width: 60px; max-width: 230px;" value="" />
    </div>
    <br />
    <div class="box-content">
        <label class="control-label" for="shiftName">Operator</label>
        <div id="OperatorGrid"></div>
        <div class="clearfix"></div>
    </div>
</div>

我的JavaScript:

//Initialize Kendo DDL
$(document).ready(function () {
        $("#ShiftInputs").kendoComboBox({
            dataTextField: "text",
            dataValueField: "value",
            dataSource: ShiftData,
            index: 0,
            change: onChange
        });

        //Loading Kendo Grid with all data
        $("#OperatorGrid").data("kendoGrid").dataSource.read();
    });

//DDL values
var ShiftData = [{ text: "ALL", value: "ALL" }, { text: "DAY", value: "DAY" }, { text: "NIGHT", value: "NIGHT" }];

//DDL change event function, hitting Home controller, function StatusCmbChanged.

    function onChange() {
        var statusValue = $("#ShiftInputs").val();
        $.ajax({
            url: 'Home/StatusCmbChanged',
            type: "POST",
            data: { "statusValue": statusValue },
            dataType: "json"
        }).done(delayedRefresh());
    }

    function delayedRefresh() {
        window.setTimeout(Refresh, 500);
    }

    function Refresh() {
        $("#RefreshMessage").show("slow").delay(5000).hide("slow");
        $("#OperatorGrid").data("kendoGrid").dataSource.read();
    }

    //Main Kendo Grid
    $("#OperatorGrid").kendoGrid({

        dataSource: {

            transport: {
                read: {
                    url: "Home/GetOperatorData",
                    type: "POST",
                    contentType: "application/json",
                    dataType: "json"
                },
                update: {
                    url: "UpdateOperatorData",
                    contentType: "application/json; charset=utf-8",
                    type: "POST",
                    dataType: "json"
                },
                parameterMap: function (data, operation) {
                    if (operation != "read") {
                        return kendo.stringify(data.models);
                    }
                }
            },

            serverPaging: false,
            pageSize: 10,            
            schema: {
                model: {
                    id: "ID",
                    fields: {
                        ID: { editable: false },
                        Title: { validation: { required: true } },
                        Name: { editable: true },
                        Hours: { editable: true, type: "number", validation: { required: true, min: 0, step: 0.25 } },
                        Shift: { editable: true },
                        Comments: { editable: true }
                    }
                }
            }    
        },

        pageable: {
            refresh: true,
            pageSizes: true
        },
        sortable: true,
        autoBind: false,

        columns:
        [
            { field: "Title", width: 100 },
            { field: "Name", width: 120 },            
            { field: "Hours", width: 100 },
            { field: "Shift", width: 100 },
            { field: "Comments", width: 100 },            
        ]
    });

我的 MVC 代码:控制器:

public ActionResult Index()
        {    
            return View();
        }

我的网格数据表:

static DataTable GetTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Title", typeof(string));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Hours", typeof(int));
            table.Columns.Add("Shift", typeof(string));
            table.Columns.Add("Comments", typeof(string));

            table.Rows.Add(0, "Mr", "Indocin David", 12, "DAY", "Good sprit");
            table.Rows.Add(1, "Mr", "Enebrel Sam", 8, "NIGHT", "");
            table.Rows.Add(2, "Dr", "Hydralazine Christoff", 12, "DAY", "");
            table.Rows.Add(3, "Mrs", "Combivent Janet", 12, "DAY", "");
            table.Rows.Add(4, "Miss", "Dilantin Melanie", 8, "NIGHT", "Lazy");
            table.Rows.Add(5, "Mr", "Tim Melanie", 14, "DAY", "");
            table.Rows.Add(6, "Mr", "Robin Sriboski", 6, "NIGHT", "");
            table.Rows.Add(7, "Mrs", "Anna Frank", 13, "NIGHT", "");
            table.Rows.Add(8, "Mr", "Dimitri Petrovich", 9, "DAY", "Hard worker");
            table.Rows.Add(9, "Mr", "Roberto Carlos", 7, "NIGHT", "");
            table.Rows.Add(10, "Mrs", "Stepheny Abraham Lincoln", 13, "DAY", "");

            return table;
        }

我的剑道网格阅读:

[HttpPost]
        public ContentResult GetOperatorData([DataSourceRequest]DataSourceRequest request)
        {
            string OperatorJsonData = "";

            DataTable table = GetTable();

            string Shift = Session["CurrentShift"] as string;

            if (!string.IsNullOrEmpty(Shift) && (Shift == "DAY" || Shift == "NIGHT"))
            {
                OperatorJsonData = JsonConvert.SerializeObject(from myRow in table.AsEnumerable()
                                                               where myRow.Field<string>("Shift") == Shift
                                                               select new
                                                               {
                                                                   ID = myRow.Field<int>("ID"),
                                                                   Title = myRow.Field<string>("Title"),
                                                                   Name = myRow.Field<string>("Name"),
                                                                   Hours = myRow.Field<int>("Hours"),
                                                                   Shift = myRow.Field<string>("Shift"),
                                                                   Comments = myRow.Field<string>("Comments")
                                                               });

            }
            else
            {
                OperatorJsonData = JsonConvert.SerializeObject(table);
            }

            return new ContentResult { Content = OperatorJsonData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
        }

我的 Kendo DropDownList onChange Ajax 调用命中点:

[HttpPost]
        public void StatusCmbChanged(string statusValue)
        {
            if (!string.IsNullOrEmpty(statusValue))
            {
                Session.Remove("CurrentShift");
                Session["CurrentShift"] = statusValue;
            }
        }

@marlonies 希望这会对您有所帮助。

所有人预览 选择 DAY 时预览 选择 NIGHT 时预览

于 2014-01-19T01:39:23.243 回答