How to bind drop-down list in ASP.Net MVC

In the previous blog, we have seen 'How to bind static values with Dropdown in MVC?'
I have collected MVC tutorial topics, please have a look.
In this blog, let's see how to bind dropdown list in MVC?

Bind dropdown list in MVC using ViewBag


First, write a function in your controller.
Below is the function you can use. Instead of a List, you may get items from SQL or any other sources that up to you.

private void GetItems()
        {
            List<string> items = new List<string>();
            items.Add("Item1");
            items.Add("Item2");
            items.Add("Item3");
            ViewBag.Items = items;
        }

Now you must call GetItems() function in your view. See Below.

public ActionResult Index()
        {
            GetItems();
            return View();
        }

Below is the .cshtml code to represent dropdown list with items.

<div class="form-group">
                                        @Html.Label("Select Items")
                                        @Html.DropDownList("Item Selection", new SelectList(ViewBag.Items as System.Collections.IEnumerable))
                                    </div>

Keep your eyes on SharePointCafe.Net for upcoming MVC blogs

You may also like below blogs -


Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers