1

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

     <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()

问题是键值始终为空:

var key = grid.GetRowKey(e.visibleIndex); ==> 始终为空

PS:e.visibleIndex不为空。

4

1 回答 1

1

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

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

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

@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()

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

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
        }
    });
}
于 2018-04-29T23:49:44.027 回答