如何绑定Kendo.MVC DataSource使用Razor页面上的Ajax Request在WebApi中读取

时间:2016-05-25 20:48:48

标签: asp.net-mvc razor asp.net-web-api kendo-grid kendo-asp.net-mvc

我有一个像

这样的网格
<script>
    $(function () {
        var grid = $("#grid").data("kendoGrid");

        grid.dataSource.transport.options.read.beforeSend = function (xhr) {
            xhr.setRequestHeader('Authorization', 'Bearer @Session["Authorization"]');
        };
        grid.dataSource.read();
    });
</script>

我想添加一个自定义授权令牌,主要是:http://www.telerik.com/forums/cannot-add-a-custom-http-header

但是当我这样做时,被发送的参数都被搞砸了,我不知道如何正确解析它们。

以下是将Header添加到数据源

的脚本
 [HttpPost, Route("Stuffs")]
public IHttpActionResult PostStuffs([DataSourceRequest] DataSourceRequest request)
    {
        if (ModelState.IsValid)
        {
            using (var entities = dboModel.Value)
            {
                var query = entities.Stuff
                    .ProjectToType<DtoStuff>();

                request = request == null ? new DataSourceRequest() : request;

                var result = query.ToDataSourceResult(request);

                return Ok(result);
            }
        }
        else
        {
            return BadRequest("Request is not Valid");
        }
    }

这里是WebApi中的控制器 Controller.cs

@(Html.Kendo().Grid<DtoStuff>()
            .Name("grid")
            .Columns(columns =>
            {
                columns.Bound(c => c.Number);
                columns.Bound(c => c.Date)
                columns.Bound(c => c.Total);

            })
            .Reorderable(reorderable => reorderable.Columns(true))
            .Resizable(resizable => resizable.Columns(true))
            .Pageable()
            .Filterable(f => f.Extra(false).Mode(GridFilterMode.Menu))
            .ColumnMenu()
            .AutoBind(false)
            .DataSource(dataSource => dataSource
                .Ajax()
                .ServerOperation(true)
                .PageSize(15)
                .Model(model => model.Id(p => p.Number))
                .Read(read => read
                    .Url("https://local-api.net/Customer/v1/Stuff/Stuffs")
                    .Type(HttpVerbs.Get)
                    )
                .Sort(s => s.Add("Date").Descending())
                .Filter(f => f.Add(a => a.Date).IsGreaterThanOrEqualTo(DateTime.Now.AddYears(-1)))
        )
    )

1 个答案:

答案 0 :(得分:1)

概述

客户端(CSHTML)

  1. 确保数据源读取操作不自动绑定
  2. 将数据源设置为Ajax
  3. 将ServerOperation设置为true
  4. 使用Type = GET(重要)
  5. 设置Read操作

    应该是这样的:

     $(function () {
        var grid = $("#grid").data("kendoGrid");
    
        grid.dataSource.transport.options.read.beforeSend = function (xhr) {
            xhr.setRequestHeader('Authorization', 'Bearer @Session["Authorization"]');
            if('@Session["StuffedHeader"]' != '')
            {
                xhr.setRequestHeader('StuffedHeader', '@Session["StuffedHeader"]');
            }
        };
        grid.dataSource.read();
    });
    

    客户端(脚本)

    1. 添加此处列出的beforeSend匿名函数:http://www.telerik.com/forums/cannot-add-a-custom-http-header

      [RoutePrefix("FluffyThings/v1/Stuff")]
      
      [EnableCors("*", "*","*")]
      
      public class StuffController : ApiController
      {
      
          [HttpGet, Route("Stuffs")]
      
          public IHttpActionResult Get([ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] DataSourceRequest request)
          {
              return PostStuffs(request);
          }
      
          [HttpPost, Route("Stuffs")]
      
          public IHttpActionResult PostStuffs([DataSourceRequest] DataSourceRequest request)
          {
              if (ModelState.IsValid)
              {
                  using (var entities = dboModel.Value)
                  {
                      var query = entities.stuff.ProjectToType<DtoStuff>();
      
                      request = request == null ? new DataSourceRequest() : request;
      
                      var result = query.ToDataSourceResult(request);
      
                      return Ok(result);
                  }
              }
              else
              {
                  return BadRequest("Request is not Valid");
              }
          }
      
          [HttpOptions, Route("Stuffs")]
          public HttpResponseMessage OptionsStuffs()
          {
              HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
              //Use this to allow specific origin to access content
              //response.Headers.Add("Access-Control-Allow-Origin", "*");
              response.Headers.Add("Access-Control-Allow-Methods", "POST, GET");
              response.Headers.Add("Access-Control-Max-Age", "3600");
              response.Headers.Add("Access-Control-Allow-Headers", "Authorization, StuffHeader");
      
              return response;
          }
      }
      
    2. 服务器端(Controller.cs)

      1. 创建选项请求(CORS需要)
      2. 使用此请求实现get请求:
      3.   

        [ModelBinder的(typeof运算(WebApiDataSourceRequestModelBinder))]   DataSourceRequest请求

        1. 选择添加&#39; Access-Control-Allow-Origin&#39;
        2. 的位置
        3. 使用[EnableCors(&#34; &#34;,&#34; &#34;,&#34; *&#34;)]
        4. 使用response.Headers.Add(&#34; Access-Control-Allow-Origin&#34;,&#34; *&#34;);在OptionMethod中

          reverse("word")
           reverse("ord")
            reverse("rd")
             reverse("d")
              reverse("")
             putchar('d')
            putchar('r')
           putchar('o')
          putchar('w')