【问题标题】:Binding an editor template for Kendo grid为 Kendo 网格绑定编辑器模板
【发布时间】:2015-04-02 13:23:49
【问题描述】:

我在将自定义 EditorTemplate 连接到 MVC 5 应用程序中的网格时遇到了困难。我有一个整数字段,它只接受 1 或 2 作为值。我不想使用标准的数字文本框或滑块控件,而是使用按钮(通过 Bootstrap 的组按钮)将其连接起来。如果用户点击第一个按钮,则该值应设置为 1,否则应设置为 2。

我遇到的问题是,当用户单击“编辑”按钮时,“级别”值永远不会应用于编辑器模板。模板按我的意愿显示,但我不知道如何将选定的值绑定回剑道网格。当用户单击网格上的“保存”按钮时,永远不会调用控制器操作。

如果我将编辑器模板替换为标准的 Kendo 控件,例如数字文本框或 Kendo 滑块,它可以正常工作。

视图模型

public class LotViewModel
{
   public int LotId { get; set; }
   [Display(Name = "Level")]
   [Range(1, 2)]
   [UIHint("LotLevel")]
   public int Level { get; set; }
}

查看

@(Html.Kendo().Grid<LotViewModel>()
  .Name("lotGrid")
  .Columns(columns =>
  {
    columns.Bound(x => x.LotId).Visible(false);
    columns.Bound(x => x.Level);
    columns.Command(command =>
    {
      command.Edit();
    }).Width(100);
  })
  .ToolBar(toolbar => toolbar.Create())
  .Editable(editable => editable.Mode(GridEditMode.InLine))
  .AutoBind(true)
  .DataSource(dataSource => dataSource
    .Ajax()
    .Model(model =>
    {
      model.Id(m => m.LotId);
      model.Field(m => m.Level).DefaultValue(1);
    })
    .Read(update => update.Action("GetLots", "Lot"))
    .Create(update => update.Action("CreateLot", "Lot"))
    .Update(update => update.Action("UpdateLot", "Lot"))
  )
  )

EditorTemplate:LotLevel

@model int
@{
   var levelOne = Model.Equals(1) ? "active btn-primary" : null;
   var levelTwo = Model.Equals(2) ? "active btn-primary" : null;

   var htmlField = ViewData.TemplateInfo.HtmlFieldPrefix;
 }

@Html.HiddenFor(model => model)
<div class="btn-group btn-group-@htmlField">
  <button type="button"
          class="btn btn-default @levelOne bool-@htmlField"
          onclick="javascript: setValue(this, 1);">
    Level 1
  </button>
  <button type="button"
          class="btn btn-default @levelTwo bool-@htmlField"
          onclick="javascript:setValue(this, 2);">
    Level 2
  </button>
</div>

<script>
  function setValue(button, level) {
    $('.btn-group-@htmlField button.active').removeClass('active btn-primary');
    $(button).addClass('active btn-primary');
    $('#@htmlField').val(level); // TODO: Set the value of the model here
  }
</script>

【问题讨论】:

    标签: asp.net-mvc-5 kendo-grid kendo-asp.net-mvc mvc-editor-templates


    【解决方案1】:

    归结为绑定。编辑器模板在创建网格时实例化一次(使用空模型对象)然后隐藏。当您单击“编辑”时,编辑器被放置到 DOM 中,替换显示行,并且 dataSource 对象中的值绑定到编辑器模板中的输入(我认为是按名称)。使用标准或剑道输入,这会导致编辑器更新并显示正确的值。使用复杂的编辑器(或复杂的对象),绑定基本上会失败并且不会继续。

    在您的情况下,您可以向 Grid 的编辑事件添加一个事件处理程序,该事件将在显示编辑器时强制按钮更新为输入值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      • 1970-01-01
      相关资源
      最近更新 更多