How to bind ejDropDownList to a MVC list?
Description
Populate the DropDownList control by using generic list.
Solution
To bind the DropDownList by using MVC generic list, the list of values from controller to the view is passed as illustrated in the following code example.
CS
List<Bikes> bike = new List<Bikes>(); // Create the list to add the dropdown items public ActionResult DropdownlistFeatures() { bike.Add(new Bikes { bikeid = "bk1", text = "Apache RTR" }); bike.Add(new Bikes { bikeid = "bk2", text = "CBR 150-R" }); bike.Add(new Bikes { bikeid = "bk3", text = "CBZ Xtreme" }); bike.Add(new Bikes { bikeid = "bk4", text = "Discover" }); bike.Add(new Bikes { bikeid = "bk5", text = "Dazzler" }); return View(bike); }
Create the class “Bikes” and define the properties in that class section, so that it is used in the controller. Refer to the following code to define the class.
public class Bikes { public string text { get; set; } public string bikeid { get; set; } } |
Create the strongly typed view by using generic list class, to get the list of values as illustrated in the following code example.
CSHTML
@model List<Bikes> <div class="ctrllabel"> Select a Bike</div> @*Element to Render Dropdown list*@ <input type="text" id="bikeList" /> </div> <script> $(function () { // Get and assign the MVC List data to local data variable var data=@Html.Raw(Json.Encode(Model)); $('#bikeList').ejDropDownList({ //Assign the DataSource value to dropdownlist control. dataSource: data, // Mapping the fields fields: { id: "bikeid", text: "text", value: "text" } }); }); </script>
In the dropdown list fields property, you can pass the following parameters other than id, text, value;
htmlAttributes,imageAttributes, imageUrl,selected,SpriteCssClass,tableName
API Reference: https://help.syncfusion.com/api/js/ejdropdownlist
Demo: https://ej2.syncfusion.com/aspnetmvc/DropDownList/DataBinding#/bootstrap5
UG documentation: https://help.syncfusion.com/js/overview
Conclusion
I hope you enjoyed learning about how to bind ejDropDownList to a MVC list.
You can refer to our ASP.NET MVC Dropdownlist feature tour page to know about its other groundbreaking feature representations. You can also explore our documentation to understand how to present and manipulate data.
For current customers, you can check out ASP.NET Core components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our ASP.NET Core DocIo and other ASP.NET Core components.
If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!