Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Part 34 Generating a dropdownlist control in mvc using HTML helpers

Автор: kudvenkat

Загружено: 2013-06-09

Просмотров: 308379

Описание:

To generate a dropdownlist, use DropDownList html helper. A dropdownlist in MVC is a collection of SelectListItem objects. Depending on your project requirement you may either hard code the values in code or retrieve them from a database table. In this video, we will discuss both the approaches.

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.
   / @aarvikitchen5572  

Generating a dropdownlist using hard coded values: We will use the following overloaded version of "DropDownList" html helper.
DropDownList(string name, IEnumerable[SelectListItem] selectList, string optionLabel)

The following code will generate a departments dropdown list. The first item in the list will be "Select Department".
@Html.DropDownList("Departments", new List[SelectListItem]
{
new SelectListItem { Text = "IT", Value = "1", Selected=true},
new SelectListItem { Text = "HR", Value = "2"},
new SelectListItem { Text = "Payroll", Value = "3"}
}, "Select Department")

The downside of hard coding dropdownlist values with-in code is that, if we have to add or remove departments from the dropdownlist, the code needs to be modified.

In most cases, we get values from the database table. For this example, let's use entity framework to retrieve data. Add ADO.NET entity data model. We discussed working with entity framework in Parts 8 & 25.

To pass list of Departments from the controller, store them in "ViewBag"
public ActionResult Index()
{
// Connect to the database
SampleDBContext db = new SampleDBContext();
// Retrieve departments, and build SelectList
ViewBag.Departments = new SelectList(db.Departments, "Id", "Name");

return View();
}

Now in the "Index" view, access Departments list from "ViewBag"
@Html.DropDownList("Departments", "Select Department")

Text version of the video
http://csharp-video-tutorials.blogspo...

Slides
http://csharp-video-tutorials.blogspo...

All ASP .NET MVC Text Articles
http://csharp-video-tutorials.blogspo...

All ASP .NET MVC Slides
http://csharp-video-tutorials.blogspo...

All Dot Net and SQL Server Tutorials in English
https://www.youtube.com/user/kudvenka...

All Dot Net and SQL Server Tutorials in Arabic
   / kudvenkatarabic  

Part 34   Generating a dropdownlist control in mvc using HTML helpers

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Part 35   How to set an item selected when an asp net mvc dropdownlist is loaded

Part 35 How to set an item selected when an asp net mvc dropdownlist is loaded

Part 37   Generating a radiobuttonlist control in mvc using HTML helpers

Part 37 Generating a radiobuttonlist control in mvc using HTML helpers

Part 47   Displaying images in asp net mvc

Part 47 Displaying images in asp net mvc

Part 10  Working with multiple tables in mvc

Part 10 Working with multiple tables in mvc

Part 33   Html helpers in mvc

Part 33 Html helpers in mvc

💥В

💥В "Орешнике" нашли ДЕТАЛИ ВРЕМЕН ГАГАРИНА, Ракета не пробила ДАЖЕ КРЫШУ ЗАВОДА - НАКИ

⚡️СРОЧНО! Трагедия в Чечне: Сын КАДЫРОВА в реанимации. ЖУТКАЯ АВАРИЯ прямо сейчас

⚡️СРОЧНО! Трагедия в Чечне: Сын КАДЫРОВА в реанимации. ЖУТКАЯ АВАРИЯ прямо сейчас

Для Чего РЕАЛЬНО Нужен был ГОРБ Boeing 747?

Для Чего РЕАЛЬНО Нужен был ГОРБ Boeing 747?

Самая быстрая передача файлов МЕЖДУ ВСЕМИ ТИПАМИ УСТРОЙСТВ 🚀

Самая быстрая передача файлов МЕЖДУ ВСЕМИ ТИПАМИ УСТРОЙСТВ 🚀

Стрельба в центре Москвы / Президент вводит войска?

Стрельба в центре Москвы / Президент вводит войска?

JavaScript - Полный Курс JavaScript Для Начинающих [11 ЧАСОВ]

JavaScript - Полный Курс JavaScript Для Начинающих [11 ЧАСОВ]

⚡СРОЧНОЕ обращение Путина по “СВО”! Взорвал сеть НОВЫМ ЗАЯВЛЕНИЕМ. Выдал ТАКУЮ ДИЧЬ

⚡СРОЧНОЕ обращение Путина по “СВО”! Взорвал сеть НОВЫМ ЗАЯВЛЕНИЕМ. Выдал ТАКУЮ ДИЧЬ

Я в опасности

Я в опасности

Учим HTML и CSS за 7 часов! Уроки по созданию сайтов Полный курс HTML и CSS с нуля до профессионала

Учим HTML и CSS за 7 часов! Уроки по созданию сайтов Полный курс HTML и CSS с нуля до профессионала

Перестаньте повторять формулы! Используйте функцию MAP в Excel.

Перестаньте повторять формулы! Используйте функцию MAP в Excel.

Как стать аналитиком данных в 2026 году (с 0)

Как стать аналитиком данных в 2026 году (с 0)

ДАМПЫ В JAVA на практике, разбираем проблемы

ДАМПЫ В JAVA на практике, разбираем проблемы

Google превратил Gmail в центр управления искусственным интеллектом.

Google превратил Gmail в центр управления искусственным интеллектом.

4 часа Шопена для обучения, концентрации и релаксации

4 часа Шопена для обучения, концентрации и релаксации

Python — полный курс для начинающих. Этот навык изменит твою жизнь.

Python — полный курс для начинающих. Этот навык изменит твою жизнь.

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: infodtube@gmail.com