Search code examples
javascriptdatagriddevexpressdevextreme

DevExtreme datagrid returning cell value on button click


In my project I have a simple datagrid set up as follows in a razor page:

<div id="Datagrid" dx-item-alias="itemData">
    @(Html.DevExtreme().DataGrid<Batch>().ID("gridContainer")
    .Columns(columns =>
    {
        columns.Add().CellTemplate(
          @<text>
            @(Html.DevExtreme().Button()
            .ID("sendButton")
            .Text("Select Batch")
            .OnClick("onItemClick")     
            )                          
          </text>);
        columns.AddFor(m => m.Id);
        columns.AddFor(m => m.Name).Caption("Name");
    })
    .DataSource(d => d.Mvc().Controller("Batches").LoadAction("GetAllEntries").Key("BatchId")) 
    ) 
</div>

The data is loaded into datagrid via a WebApi I've created. I'm omitting that code from my question as it doesn't add anything of value.

In the first column I have added a button for every row that gets rendered. What I want to happen is when I click on this button, the value of cell Id next to it, is rendered on the screen/console/whatever. I just need to grab the value.

A rough visual of this is:

       | Id  | Name
-------|-----|------
button |  1  | John
button |  2  | Chris

So when I press the button next to cell containing an Id value of 1, I want to grab this value and print out on the screen or console. When I press the button next to id value of 2 I want to grab the value of "2" and do the same.

I've the following js code trying to achieve this:

function onItemClick(e) {
    DevExpress.ui.notify("The " + e.component.option("value"));
  }

However, this isn't working. What do I need to do in order to get the correct cell value?


Solution

  • The easiest way to achieve this is to use the approach described in the ASP.NET MVC Controls -> Fundamentals -> Implementing Templates -> Accessing Template Parameters article. I.e. inside your Button OnClick event handler, you can use the data variable to access the current grid row:

    columns.Add().CellTemplate(
        @<text>
            @(Html.DevExtreme().Button()
                    .ID("sendButton")
                    .Text("Select Batch")
                    .OnClick("function () { onItemClick(data); }")
            )
        </text>);
    

    Then, the onItemClick method will look like:

    function onItemClick(data) {
        DevExpress.ui.notify(data.Id);
    }