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

In the previous blog, we have seen 'How to bind drop-down list in ASP.Net MVC'
I have collected MVC tutorial topics, please have a look.
In this blog, let's see how to bind dropdown list in MVC using Model?

Bind Dropdown list in MVC with SQL data

Binding drop-down in MVC is a little bit different than what we have done in traditional ASP.Net
In this blog, we will see how to bind dropdown with SQL data using Model. In the previous blog, we have seen Binding Dropdown in MVC using ViewBag.

Create an MVC project in Visual Studio any version 2012, 2013, 2015 or 2017

1. Add a class in the Model folder and name it MyModel.cs and add below code.


public class MyModel
    {
        public int Catid { get; set; }
        public string Category { get; set; }
        public List<SelectListItem> Categories { get; set; }
    }


2. Now create a controller with name Home and write code as shown below.

Name of the Action - Index
Controller Name - Home

public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            MyModel model = new MyModel();
            model.Categories = CategoryList();
            return View(model);
        }

        private static List<SelectListItem> CategoryList()
        {
            List<SelectListItem> category = new List<SelectListItem>();
            string constr = "connection string";
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "select catid, (category + ' > ' + subcategory) as maincategory from [Practice].[dbo].[ProductCategory]";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            category.Add(new SelectListItem
                            {
                                Value = dr["catid"].ToString(),
                                Text = dr["maincategory"].ToString()
                              
                            });
                        }
                    }
                    con.Close();
                }
            }

            return category;
        }
       }

3. Create a view and add below line to the top of the page.

@model WebApplicationMVc.Models.MyModel

4. Add dropdown list in your view like this.

@model WebApplicationMVc.Models.MyModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
         @Html.DropDownListFor(m => m.Catid, Model.Categories, "--Select Category--")
    </div>
</body>
</html>




Comments

Popular