HTML Helper in ASP.NET Core Part 2- Session 29

HTML Helper Part 2 - Session29-min

In this session of .NET 5.0 training course, we are going to continue our discussion about HTML Helper and will discuss about passing Select List Items from Controller to View and DropDownList Html Helper. In Session 28 we explained DropDownList and created its item list inside the View. During this session, we will show you the way that you can create the list in the Action Method and passing it to the View.

Passing SelectList from Controller to View

SelectList() is an Enumerable object that contains List of SelectListItem() which are Items of DropDownList. Thus, we need to get this list from database or a static repository or even create it inside the Action Method. In this session, we create the list inside Create Action Method of Cost Controller.

Then, we need to pass the created list to View and DropDownList() through ViewBag(). Just bear in mind, if the Dynamic Property of ViewBag() would be exactly the same as DropDownList Expression, the list will be bound automatically.

Below code is related to CostController and Create Action Method and “Rent” is selected as default item of the list.

Also, below code is related to the DropDownList() and as you can see, Dynamic Propert of ViewBag() is exactly the same as Expression of DropDownList().

But, in the above code, by default we are not able to use html Attribute and we can do below changes for solving this issue. Moreover, we can select default value of the list with “Selected” field of SelectListItem as shown it in the below code.

Hence, with the above changes “Grocery” is selected as default Item. Also, below changes solve html Attribute issue for the DropDownList().

If you need more details, watch this session video. Also, for being updated about our coming sessions, follow us on Instagram, Facebook, Telegram or YouTube. Also you can have access to list of all sessions HERE.

You can download this Session Slides form HERE

0.00 avg. rating (0% score) - 0 votes


0 0 votes
Article Rating

Inline Feedbacks
View all comments