How to add a template to a Kendo grid toolbar

2019-05-28 21:38发布

问题:

I am trying to add a custom template to Kendo MVC grid. My template should contain 2 things

  1. Create button to add new record to the grid
  2. Autocomplete box to filter the data in the grid.

I am trying the following code :

.ToolBar(toolbar =>
{
    toolbar.Template(@<text>
                <div class="toolbar">
                    <label class="category-label" for="category">Filter by name:</label>
                    @(Html.Kendo().AutoComplete()
                            .Name("employees")
                            .DataTextField("empName")
                                      .Filter("contains")
          .MinLength(3)
          .Events(e => e.Change("nameChange"))
                            .DataSource(ds =>
                            {
                                ds.Read("FilteringList", "Employee");
                            })

                        )
                </div>
                </text>);
    toolbar.Create().Text("New Record");

})

but this is not working. I can only see the autocomplete box.

Any ideas on how I can accomplish my requirements?

回答1:

Remove the below line

toolbar.Create().Text("New Record");

from the ToolBar Section and add the button inside the template. Please see below code:

.ToolBar(toolbar =>
{
toolbar.Template(@<text>
            <div class="toolbar">
                <a class="k-button k-button-icontext k-grid-add" href="/YourControllerName/YouCreateActionResultJsonName?grdSearch-mode=insert">New Record</a>
                <label class="category-label" for="category">Filter by name:</label>
                @(Html.Kendo().AutoComplete()
                        .Name("employees")
                        .DataTextField("empName")
                                  .Filter("contains")
      .MinLength(3)
      .Events(e => e.Change("nameChange"))
                        .DataSource(ds =>
                        {
                            ds.Read("FilteringList", "Employee");
                        })

                    )
            </div>
            </text>);
})


回答2:

Nitin Mall's answer can be simplified by replacing

<a class="k-button k-button-icontext k-grid-add"   
href="/YourControllerName/YouCreateActionResultJsonName?grdSearch-mode=insert">
New Record</a>

with

<a class='k-button k-button-icontext k-grid-add' 
href='#'><span class='k-icon k-add'></span>Add new record</a>

This works because the grid uses jquery delegate to attach the grid's click event handler which calls the AddRow method to the item with class "k-grid-add"