Devexpress MVC5 Grid GetRowKey(e.visibleIndex)返回null

时间:2018-04-29 22:53:59

标签: asp.net-mvc gridview devexpress-mvc onrowclick

大家好我试图获取所选行的主键,以便稍后将其发送到服务器,这是代码: 这是主页

     <script type="text/javascript">
        function OnRowClick(s, e) {
        var grid = MVCxClientGridView.Cast(s);
        var key = grid.GetRowKey(e.visibleIndex);
        console.log(key);

        $.ajax({
          url: '@Url.Action("FundDetails", "Fund")',
          type: "POST",
          dataType: "text",
          traditional: true,
          data: { rowKey: key },
          success: function (data) {
          console.log(data);
          },
          error: function (xhr, textStatus, errorThrown) {
          alert('Request Status: ' + xhr.status + '; Status Text: ' + textStatus + 
          '; Error: ' + errorThrown);
          }
          });
           }
    </script>

<div>
@Html.Partial("_FundsList", Model)
</div>

这是包含Grid

的局部视图
  @Html.DevExpress().GridView(settings =>
  {

  settings.Name = "FundGrid";
  settings.CallbackRouteValues = new { Controller = "Fund", Action = 
  "FundsList" };
  settings.Width = 450;
  settings.Columns.Add("codeIsin");
  settings.Columns.Add("fundLabel");
  settings.Columns.Add("variation");
  settings.Columns.Add("ClassNiv1");
  settings.SettingsBehavior.AllowSelectByRowClick = true;
  settings.SettingsBehavior.AllowSelectSingleRowOnly = true;
  settings.ClientSideEvents.RowClick = "OnRowClick";
  }).Bind(Model).GetHtml()

问题是键值始终为null:

var key = grid.GetRowKey(e.visibleIndex); ==&gt;总是空的

PS: e.visibleIndex 不为空。

1 个答案:

答案 0 :(得分:1)

GetRowKey方法解释了如何返回null值:

  

如果通过visibleIndex参数传递的索引错误,或者   ASPxGridBase.KeyFieldName属性未设置,返回null。

您可能需要在GridView中设置引用主键和/或标识字段(具有唯一值)的KeyFieldName,如下例所示:

@Html.DevExpress().GridView(settings =>
{
    settings.Name = "FundGrid";
    settings.CallbackRouteValues = new { Controller = "Fund", Action = "FundsList" };
    settings.Width = 450;
    settings.Columns.Add("codeIsin");
    settings.Columns.Add("fundLabel");
    settings.Columns.Add("variation");
    settings.Columns.Add("ClassNiv1");

    // set primary/identity key field to determine selected row index
    settings.KeyFieldName = "codeIsIn";

    settings.SettingsBehavior.AllowSelectByRowClick = true;
    settings.SettingsBehavior.AllowSelectSingleRowOnly = true;
    settings.ClientSideEvents.RowClick = "OnRowClick";
}).Bind(Model).GetHtml()

此外,您可以在执行AJAX调用之前使用if条件进行空值检查,以确保正确传递关键字段值:

var key = grid.GetRowKey(e.visibleIndex);

if (key != null)
{
    $.ajax({
        url: '@Url.Action("FundDetails", "Fund")',
        type: "POST",
        data: { rowKey: key },
        // other AJAX settings
        success: function (data) {
            // do something
        },
        error: function (xhr, textStatus, errorThrown) {
            // error handling
        }
    });
}