Getting Started with the SegmentedControl
This tutorial explains how to set up a basic Telerik UI for ASP.NET MVC SegmentedControl and highlights the major steps in the configuration of the component.
You will initialize a SegmentedControl with several items, configure icons, set a default selection, and handle the Change event.
Prerequisites
To successfully complete the tutorial, you need a project that is already configured to use the Telerik UI for ASP.NET MVC components:
-
To create a new pre-configured project for the Telerik UI for ASP.NET MVC components, you can use a project template.
-
To manually configure an existing project by using NuGet, see the Adding Telerik UI through NuGet.
1. Prepare the CSHTML File
The first step is to add the required directives at the top of the .cshtml document:
-
To use the Telerik UI for ASP.NET MVC HtmlHelpers:
Razor@using Kendo.Mvc.UI
2. Initialize the SegmentedControl
Use the SegmentedControl HtmlHelper to add the component to a page. The Name() configuration method is mandatory as its value is used for the id and the name attributes of the SegmentedControl element.
@using Kendo.Mvc.UI
@(Html.Kendo().SegmentedControl()
.Name("segmentedControl")
)
3. Add Items
Use the Items() configuration to define the selectable segments. Each item requires a Text() and a Value().
@using Kendo.Mvc.UI
@(Html.Kendo().SegmentedControl()
.Name("segmentedControl")
.Items(items =>
{
items.Add().Text("Day").Value("day");
items.Add().Text("Week").Value("week");
items.Add().Text("Month").Value("month");
})
)
4. Add Icons
Enhance the visual representation of the items by adding icons with the Icon() option.
@using Kendo.Mvc.UI
@(Html.Kendo().SegmentedControl()
.Name("segmentedControl")
.Items(items =>
{
items.Add().Text("Day").Value("day").Icon("calendar");
items.Add().Text("Week").Value("week").Icon("clock");
items.Add().Text("Month").Value("month").Icon("calendar-date");
})
)
5. Set a Default Selection
Use SelectedValue() to pre-select one of the items when the component renders.
@using Kendo.Mvc.UI
@(Html.Kendo().SegmentedControl()
.Name("segmentedControl")
.Items(items =>
{
items.Add().Text("Day").Value("day").Icon("calendar");
items.Add().Text("Week").Value("week").Icon("clock");
items.Add().Text("Month").Value("month").Icon("calendar-date");
})
.SelectedValue("week")
)
6. Handle the Change Event
Use the Events() configuration to subscribe to the Change event and react when the user selects a different segment.
@using Kendo.Mvc.UI
@(Html.Kendo().SegmentedControl()
.Name("segmentedControl")
.Items(items =>
{
items.Add().Text("Day").Value("day").Icon("calendar");
items.Add().Text("Week").Value("week").Icon("clock");
items.Add().Text("Month").Value("month").Icon("calendar-date");
})
.SelectedValue("week")
.Events(ev => ev.Change("onChange"))
)
<script>
function onChange(e) {
console.log("Selected value: " + e.value);
}
</script>