【问题标题】:How to bind the kendo dropdownlist to asp.net web api without ajax call?如何在没有 ajax 调用的情况下将 kendo 下拉列表绑定到 asp.net web api?
【发布时间】:2017-06-27 09:36:17
【问题描述】:

我有一个剑道下拉列表。我正在对我的 web api 进行 ajax 调用以绑定它。 下拉列表:

@(Html.Kendo().DropDownList()
            .Name("ddlDepartment")
            .DataValueField("DeptId")
            .DataTextField("DeptName")
            .SelectedIndex(0)
            .AutoBind(false)
            )

对 Web Api 的 Ajax 调用:

 $(document).ready(function () {
            var ddl = $('#ddlDepartment').data("kendoDropDownList");
            jQuery.support.cors = true;
            $.ajax({
                url: 'http://localhost:8648/api/dropdown/',
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    debugger;
                    alert(data);
                    ddl.setDataSource(data);
                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        })

但我想直接将它与 Api 绑定,就像我们在默认 mvc 控制器中使用普通操作方法绑定它一样。 我的 API 方法:

// GET api/dropdown
        public IEnumerable<Department> Get()
        {
            List<Department> depart = _departmentTask.GetAll();
            return depart;
        } 

【问题讨论】:

    标签: jquery ajax asp.net-mvc asp.net-web-api


    【解决方案1】:

    查看:

    @(Html.Kendo().DropDownList()
              .Name("products")
              .HtmlAttributes(new { style = "width: 250px" })
              .DataTextField("DeptName")
              .DataValueField("DeptId")
              .DataSource(source => {
                  source.Read(read =>
                  {
                      read.Url("http://localhost:8648/api/dropdown/").Type(HttpVerbs.Get);
                  }); 
              })
    

    API:

    // GET api/dropdown
            public IEnumerable<Department> Get()
            {
                List<Department> depart = _departmentTask.GetAll();
                return depart;
            }
    

    【讨论】:

    • 您可以考虑使用@Url.Action 来生成数据源读取url。这样一来,您在发布后就不会有任何不好的惊喜。
    【解决方案2】:

    假设你的控制器叫dropdown,你的动作叫Get,你可以bind the dropdown to a remote data source

    @(Html.Kendo().DropDownList()
     .Name("ddlDepartment")
     .DataValueField("DeptId")
     .DataTextField("DeptName")
     .SelectedIndex(0)
     .DataSource(source =>
      {
           source.Read(read =>
           {
               read.Action("Get", "dropdown");
    
           });
    )
    

    请注意,您可能需要更改控制器以返回 JsonResult

    有一个幕后的 Ajax 调用,但 Kendo 会为您处理。你也可以bind events to the Ajax call as depicted in the online demos

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多