Dropdownlist Binding in MVC

Unknown | 10:08 AM |


BranchAdmin (Model)

  public string branchid { get; set; }
  public IEnumerable<SelectListItem> BranchOptions { get; set; }
   
AdminController (Controller)

   [HttpGet]
        public ActionResult AddBranchAdmin()
        {
            var model = new BranchAdmin ();
            // Populate the dropdown options
            model.BranchOptions = GetBranches("0"); // Set the default to American Express
         
            return View(model);
        }
        private List<SelectListItem> GetBranches(string defaultValue)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Select", Value = "0", Selected = (defaultValue == "0") });
            SqlCommand cmd = new SqlCommand("select id,branch from Branch", cn);
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                items.Add(new SelectListItem { Text = dr["branch"].ToString(), Value = dr["id"].ToString() });
            }      
            dr.Close();
            cn.Close();

            return items;
        }

AddBranchAdmin (View)

@model CabAutomationSystem.Models.BranchAdmin

  <div class="editor-field">                
                     @Html.DropDownListFor(model => model.branchid, new SelectList(Model.BranchOptions, "Value", "Text"))
                 
                    @Html.ValidationMessageFor(m => m.branch)
                </div>
               

Category:

About http://dotnetvisual.blogspot.in/:
DOT NET TO ASP.NET is a web application framework marketed by Microsoft that programmers can use to build dynamic web sites, web applications and web services. It is part of Microsoft's .NET platform and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime, allowing programmers to write ASP.NET code using any Microsoft .NET language. create an application very easily ....