New to Telerik UI for ASP.NET MVC? Start a free 30-day trial
Bind Map to View Model
Environment
Product | Map for Telerik UI for ASP.NET MVC |
Product Version | Created with version 2024.4.1112 |
Description
How can I bind the ASP.NET MVC Map component to a Model collection?
Solution
MVC enables you to natively bind parts of the page to the Model that is passed from the controller.
Using this technique, you can also bind Telerik UI for ASP.NET MVC Map options to the Model properties and populate the Map markers based on a collection that is defined in the Model.
- Set up the Models.
C#
public class Map
{
// The Map properties.
public string Name { get; set; }
public double CenterLatitude { get; set; }
public double CenterLongitude { get; set; }
public int Zoom { get; set; }
// The tile layer properties.
public string TileUrlTemplate { get; set; }
public string[] TileSubdomains { get; set; }
public string TileAttribution { get; set; }
// The markers collection.
public IEnumerable<Marker> Markers { get; set; }
}
- Set up the desired data in the Controller and send it to the View.
C#
public ActionResult Index()
{
var map = new TelerikMvcApp.Models.Map()
{
Name = "MyMap",
CenterLatitude = 30.268107,
CenterLongitude = -97.744821,
Zoom = 3,
TileUrlTemplate = "http://#= subdomain #.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png",
TileSubdomains = new string[] { "a", "b", "c" },
TileAttribution = "© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>",
Markers = new List<Marker>
{
new Marker(30.268107, -97.744821, "Austin, TX")
}
};
return View(map);
}
- Configure the Map using the Model properties accessible in the View.
Razor
@model TelerikMvcApp.Models.Map
@(Html.Kendo().Map()
.Name(Model.Name)
.Center(Model.CenterLatitude, Model.CenterLongitude)
.Zoom(Model.Zoom)
.Layers(layers => layers
.Add()
.Type(MapLayerType.Tile)
.UrlTemplate(Model.TileUrlTemplate)
.Subdomains(Model.TileSubdomains)
.Attribution(Model.TileAttribution)
)
.Markers(markers =>
{
foreach (var marker in Model.Markers)
{
markers.Add()
.Location(marker.latlng)
.Title(marker.name);
}
})
)