如何让我的剑道下拉列表直播? ?_?

时间:2014-01-16 05:48:11

标签: jquery kendo-ui kendo-dropdown

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

这是我的代码:

@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

2 个答案:

答案 0 :(得分: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());
}

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

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

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

现在在服务器端以某种方式可以读取onDDLSelect()为kendo网格保存的值。一些检查,如果您的下拉值是否存在。如果存在,则执行查询所选值,否则查询全部。

[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.com/web/dropdownlist/events.html

答案 1 :(得分:1)

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

我的HTML:我已将kendo和常规标记所需的css / js文件链接到hook 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 };
        }

My Kendo DropDownList onChange Ajax call hit point:

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

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

Preview for All Preview when select DAY Preview when select NIGHT