Fundamentals

DevExtreme ASP.NET MVC Controls are a set of server-side controls that allow you to configure JavaScript-based DevExtreme widgets using familiar Razor syntax. The Razor constructions are rendered into the HTML and JavaScript needed to initialize a DevExtreme widget.

DevExtreme ASP.NET MVC Controls - JavaScript Generated from Razor Code

This guide offers the basics in DevExtreme ASP.NET MVC Controls, such as creating and configuring a DevExtreme widget, handling the events and implementing templates.

See Also

Creating a Widget

To create any DevExtreme widget, start with calling the DevExtreme() HtmlHelper extension method. Then, call the builder method corresponding to the widget you want to create.

Razor C#
Razor VB
@(Html.DevExtreme()
    .Button() // creates the Button widget
)
@(Html.DevExtreme() _
    .Button() ' creates the Button widget
)

If you are creating a widget inside a code block, end the widget configuration with a call of the Render() method.

Razor C#
Razor VB
@{
    Html.DevExtreme().Button()
        // ...
        // other options of the Button widget go here
        // ...
        .Render()
}
@Code
    Html.DevExtreme().Button() _
        @* ...
           other options of the Button widget go here
           ... *@
        .Render()
End Code

Specifying the Options

DevExtreme ASP.NET MVC Controls mirror the options of the client-side widgets with only one difference: instead of the lower camel case usual in JavaScript, control methods use the upper camel case common in .NET. For example:

Widget Option Control Method
dataSource DataSource
tooltip Tooltip
showColumnHeaders ShowColumnHeaders

Control methods are called using a fluent interface. In Visual Studio, IntelliSense prompts you the names of available methods, their accepted values and short descriptions.

DevExtreme ASP.NET MVC Controls - InstelliSense

To specify a simple widget option, call the corresponding control method and pass the required option value.

Razor C#
Razor VB
@(Html.DevExtreme().Button()
    .ID("submitButton") // sets the "id" attribute of the widget container
    .Text("submit") // sets the button text
    .Width(100) // sets the button width
)
@(Html.DevExtreme().Button() _
    .ID("submitButton") _
    .Text("submit") _
    .Width(100)
)
NOTE
Specifying the ID option is not necessary, however, you may need it if you plan to access the widget JavaScript API at runtime (to call a method, for example). The value of the ID option should meet certain requirements. It must always be unique in the context of a page. If a partial view is loaded multiple times, each instance of this partial view must render all widgets with unique IDs. Also, the value of the ID option should meet the requirements for the id attribute in HTML5.

Nested options are configured using lambda expressions. A lambda parameter starts a new chain of methods that specify the nested options.

Razor C#
Razor VB
@(Html.DevExtreme().Chart()
    .Legend(l => l // configures the chart legend (l - lambda parameter)
        .Visible(false) // hides the legend in the chart
    )
    .Tooltip(t => t // configures the tooltip (t - lambda parameter)
        .Enabled(true) // enables the tooltip
        .Font(f => f // configures the tooltip's text (f - lambda parameter)
            .Color("blue") // paints the tooltip's text in blue
        )
    )
)
@(Html.DevExtreme().Chart() _
    .Legend(Sub(l)
        l.Visible(False)
    End Sub) _
    .Tooltip(Sub(t)
        t.Enabled(True) _
         .Font(Sub(f)
             f.Color("blue")
         End Sub)
    End Sub)
)

Options that represent collections of items are configured using lambda expressions as well, but in this case, the lambda parameter performs the role of an item factory. Its Add() method adds a new item to the collection and then returns it for further configuration by the chain that follows.

Razor C#
Razor VB
@(Html.DevExtreme().DataGrid()
    .Columns(columns => { // specifies a collection of columns
        columns.Add() // adds the "CustomerID" column
            .DataField("CustomerID");

        columns.Add() // adds the "OrderDate" column
            .DataField("OrderDate")
            .DataType(GridColumnDataType.Date);
    })
)
@(Html.DevExtreme().DataGrid() _
    .Columns(Sub(columns)
        columns.Add() _
            .DataField("CustomerID")

        columns.Add() _
            .DataField("OrderDate") _
            .DataType(GridColumnDataType.Date)
    End Sub)
)

Options that accept a predefined set of values are specified by .NET enums. Refer to the description of a particular option to learn if this option accepts a enum.

Razor C#
Razor VB
@(Html.DevExtreme().DateBox()
    .Type(DateBoxType.DateTime) // sets the type using the DateBoxType .NET enum
)
@(Html.DevExtreme().DateBox() _
    .Type(DateBoxType.DateTime) ' sets the type using the DateBoxType .NET enum
)

More examples on each case are available in our technical demos and sample applications.

Handling Events and Defining Callbacks

Event handlers and callbacks are defined by JavaScript functions which can be specified in the following manners.

  • A short inline function.

    Razor C#
    Razor VB
    @(Html.DevExtreme().Button()
        .OnClick("function () { alert('The button was clicked'); }")
    )
    
    
    @(Html.DevExtreme().VectorMap()
        .Tooltip(t => t
            .CustomizeTooltip("function (arg) { return { text: arg.attribute('text') } }")
        )
    )
    @(Html.DevExtreme().Button() _
        .OnClick("function () { alert('The button was clicked'); }")
    )
    
    
    @(Html.DevExtreme().VectorMap() _
        .Tooltip(Sub(t)
            t.CustomizeTooltip("function (arg) { return { text: arg.attribute('text') } }")
        End Sub)
    )
  • An external function.

    Razor C#
    Razor VB
    @(Html.DevExtreme().Button()
        .OnClick("myButton_click")
    )
    
    
    @(Html.DevExtreme().VectorMap()
        .Tooltip(t => t
            .CustomizeTooltip("vectorMap_tooltip_customizeTooltip")
        )
    )
    
    
    <script>
        function myButton_click() {
            alert("The button was clicked");
        }
        function vectorMap_tooltip_customizeTooltip (arg) {
            return { text: arg.attribute("text") };
        }
    </script>
    @(Html.DevExtreme().Button() _
        .OnClick("myButton_click")
    )
    
    
    @(Html.DevExtreme().VectorMap() _
        .Tooltip(Sub(t)
            t.CustomizeTooltip("vectorMap_tooltip_customizeTooltip")
        End Sub)
    )
    
    
    <script>
        function myButton_click() {
            alert("The button was clicked");
        }
        function vectorMap_tooltip_customizeTooltip (arg) {
            return { text: arg.attribute("text") };
        }
    </script>
  • A function wrapped into the Razor <text> tag (C# only).

    Razor C#
    @(Html.DevExtreme().Button()
        .OnClick(@<text>
            function () {
                alert("The button was clicked");
            }
        </text>)
    )
    
    
    @(Html.DevExtreme().VectorMap()
        .Tooltip(t => t
            .CustomizeTooltip(@<text>
                function (arg) {
                    return { text: arg.attribute("text") };
                }
            </text>)
        )
    )

Calling Methods

To call widget methods, use JavaScript, much like you did to handle widget events. For instance, let's say you have a Popup widget.

Razor C#
Razor VB
@(Html.DevExtreme().Popup()
    .ID("popup")
)
@(Html.DevExtreme().Popup() _
    .ID("popup")
)

This widget appears on the page only after its show() method was called. The following code demonstrates how to call this method.

$("#popup").dxPopup("show");

You can put this code in any JavaScript constructions and execute it whenever you need to, for example, when a user clicks a button...

Razor C#
Razor VB
@* ... *@
@(Html.DevExtreme().Button()
    .OnClick("showPopup")
)
<script>
    function showPopup() {
        $("#popup").dxPopup("show");
    }
</script>
@* ... *@
@(Html.DevExtreme().Button() _
    .OnClick("showPopup")
)
<script>
    function showPopup() {
        $("#popup").dxPopup("show");
    }
</script>

... or once your page is ready.

// ...
<script>
    $(showPopup);

    function showPopup() {
        $("#popup").dxPopup("show");
    }
</script>

If the method you are calling accepts arguments, pass them after the method's name. For example, the following code calls the toggle(showing) method of the Popup widget with true as an argument.

$("#popup").dxPopup("toggle", true);
See Also
  • API Reference | WidgetName | Methods - lists all methods of a specific DevExtreme widget.

Implementing Templates

Templates in DevExtreme ASP.NET MVC Controls support ERB-style syntax. The following constructions are available.

  • <% code %> - executes the code.
  • <%= value %> - prints the value.
  • <%- value %> - prints the value escaping HTML.

There are four ways to declare templates in DevExtreme ASP.NET MVC Controls.

  • Short inline templates
    These templates support HTML and ERB-style constructions.

    Razor C#
    Razor VB
    @(Html.DevExtreme().Popup()
        .TitleTemplate("<b>Title</b>")
    )
    @(Html.DevExtreme().Popup() _
        .TitleTemplate("<b>Title</b>")
    )
    Razor C#
    Razor VB
    @(Html.DevExtreme().List()
        .ItemTemplate("<div><%= ProductName %></div>")
    )
    @(Html.DevExtreme().List() _
        .ItemTemplate("<div><%= ProductName %></div>")
    )
  • Templates with Razor helpers
    Apart from HTML and ERB-style constructions, these templates support Razor helpers. Frequently, such templates are used to nest one widget in another. For example, the following code nests the DataGrid widget in the Popup widget. Note that for high-level nesting, you need to use an external template (see below).

    Razor C#
    Razor VB
    @* Configures the Popup widget *@
    @(Html.DevExtreme().Popup()
        // ...
        // Specifies the contents of the Popup widget
        .ContentTemplate(@<text>
            // Configures the DataGrid widget
            @(Html.DevExtreme().DataGrid()
                .DataSource(d => d.WebApi().Controller("GridData"))
                .Columns(columns => {
                    columns.Add().DataField("DataField1");
                    columns.Add().DataField("DataField2");
                    columns.Add().DataField("DataField3");
                    columns.Add().DataField("DataField4");
                })
            )
        </text>)
    )
    @Code
        @* Configures the Popup widget *@
        Html.DevExtreme().Popup() _
            .ContentTemplate(Sub()
                @<text>
                    @* Configures the DataGrid widget *@
                    @(Html.DevExtreme().DataGrid() _
                        .DataSource(Function(d) d.WebApi().Controller("GridData")) _
                        .Columns(Sub(columns)
                            columns.Add().DataField("DataField1")
                            columns.Add().DataField("DataField2")
                            columns.Add().DataField("DataField3")
                            columns.Add().DataField("DataField4")
                        End Sub)
                    )
                </text>
            End Sub).Render()
    End Code
  • External templates
    External templates can be declared in a partial view or a @helper block (MVC 3, 4, 5 only). Commonly, you need to declare an external template for high-level nesting or if you want to reuse it. For example, you have the Popup widget with the List widget nested in it using a template. The List, in turn, nests another template for its items. The following examples show how you can declare the List widget in this case.

    • Partial view

      • InnerList.cshtml / InnerList.vbhtml

        Razor C#
        Razor VB
        @(Html.DevExtreme().List()
            .ItemTemplate(@<text>
                <div><%= ProductName %></div>
                <div><%= UnitPrice %></div>
            </text>)
        )
        @Code
            Html.DevExtreme().List() _
                .ItemTemplate(Sub()
                    @<text>
                        <div><%= ProductName %></div>
                        <div><%= UnitPrice %></div>
                    </text>
                End Sub).Render()
        End Code
      • Popup.cshtml / Popup.vbhtml

        Razor C#
        Razor VB
        @(Html.DevExtreme().Popup()
            .ContentTemplate(@<text>
                @(Html.Partial("InnerList"))
            </text>)
        )
        @Code
            Html.DevExtreme().Popup() _
                .ContentTemplate(Sub()
                    @<text>
                        @(Html.Partial("InnerList"))
                    </text>
                End Sub).Render()
        End Code
    • @helper (MVC 3, 4, 5 only)

      Razor C#
      Razor VB
      @(Html.DevExtreme().Popup()
          .ContentTemplate(@<text>
              @InnerList()
          </text>)
      )  
      @helper InnerList() {
          @(Html.DevExtreme().List()
              .ItemTemplate(@<text>
                  <div><%= ProductName %></div>
                  <div><%= UnitPrice %></div>
              </text>)
          )
      }
      @Code
          Html.DevExtreme().Popup() _
              .ContentTemplate(Sub()
                  @InnerList()
              End Sub).Render()
      End Code
      @helper InnerList()
          @(Html.DevExtreme().List() _
              .ItemTemplate(Sub()
                  Write(ListItem())
              End Sub)
          )
      End Helper
      @helper ListItem()
          @<text>
              <div><%= ProductName %></div>
              <div><%= UnitPrice %></div>
          </text>
      End Helper
  • JavaScript functions as templates
    Despite being a superstructure over JavaScript widgets, controls get the best from Razor syntax, but still, in some cases, Razor appears to be short of certain capabilities. In these cases, we recommend you utilize pure JavaScript backed with jQuery. Regarding templates, prefer the JavaScript function over the Razor block when you need to access JavaScript variables or implement sophisticated logic inside the template.

    Short JavaScript functions can be declared inline with the method's name using the new JS() expression.

    Razor C#
    Razor VB
    @(Html.DevExtreme().DataGrid()
        .Columns(columns => {
            columns.Add()
                .CellTemplate(new JS("function (element, cellInfo) { element.addClass('data-grid-custom-cell') }"))
                // ...
        })
    )
    @(Html.DevExtreme().DataGrid() _
        .Columns(Sub(columns)
            columns.Add() _
                .CellTemplate(New JS("function (element, cellInfo) { element.addClass('data-grid-custom-cell') }")) _
                ' ...
        End Sub)
    )

    Multi-line JavaScript functions should be declared in an external script and then referred to from the method's name using the same new JS() expression.

    Razor C#
    Razor VB
    @(Html.DevExtreme().List()
        .ItemTemplate(new JS("list_itemTemplate"))
        // ...
    )
    @(Html.DevExtreme().List() _
        .ItemTemplate(New JS("list_itemTemplate"))
        ' ...
    )
    <script>
        function list_itemTemplate(data, index, element) {
            element.append(
                $("<img />").attr("src", data.imgSrc)
            );
        }
    </script>

A common use case of templates is the detail section of the master-detail UI in the DataGrid widget. Consider the following code, in which the detail section nests another DataGrid whose controller gets the data.OrderID free variable as a loading parameter.

Razor C#
Razor VB
@(Html.DevExtreme().DataGrid()
    .DataSource(d => d.WebApi().Controller("DataGridMasterDetailView").Key("ID"))
    .Columns(columns => {
        columns.Add().DataField("FirstName");
        columns.Add().DataField("LastName");
        // ...
    })
    // Configures the master-detail UI
    .MasterDetail(md => md
        .Enabled(true)
        // Specifies the contents of the detail section
        .Template(@<text>
            @(Html.DevExtreme().DataGrid()
                .DataSource(d => d.WebApi()
                    .Controller("DataGridMasterDetailView")
                    .LoadAction("TasksDetails")
                    // Passes "ID" as a parameter to "DataGridMasterDetailViewController"
                    .LoadParams(new { id = new JS("data.ID") })
                )
            )
        </text>)
    )
)
@Code
    Html.DevExtreme().DataGrid() _
        .DataSource(Function(d) d.WebApi().Controller("DataGridMasterDetailView").Key("ID")) _
        .Columns(Sub(columns)
            columns.Add().DataField("FirstName")
            columns.Add().DataField("LastName")
            ' ...
        End Sub) _
        .MasterDetail(Sub(md)
            ' Configures the master-detail UI
            md.Enabled(True) _
            .Template(Sub()
                    @<text>
                        @(Html.DevExtreme().DataGrid() _
                            .DataSource(Function(d)
                                Return d.WebApi() _
                                        .Controller("DataGridMasterDetailView") _
                                        .LoadAction("TasksDetails") _
                                        .LoadParams(New With { .id = New JS("data.ID") }) ' Passes "ID" as a parameter
                                                                                        ' to "DataGridMasterDetailViewController"
                            End Function)
                        )
                    </text>
            End Sub)
        End Sub)
End Code

Note that the data.ID free variable is wrapped in the new JS() construction. This construction allows you to embed JavaScript statements in the resulting widget configuration. In particular, the data source configuration of the nested DataGrid from the preceding code yields the following output.

"dataSource": {
    "store": DevExpress.data.AspNet.createStore({
        "loadParams": {
            "orderID": data.ID
        },
        "loadUrl": "/api/DataGridMasterDetailView/TasksDetails",
        "insertUrl": "/api/DataGridMasterDetailView/Post",
        "updateUrl": "/api/DataGridMasterDetailView/Put",
        "deleteUrl": "/api/DataGridMasterDetailView/Delete"
    })
}

View Demo

You can find more examples of templates in our technical demos and sample applications.