Monday, August 20, 2012

Dropdownlist Binding in MVC

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>
               



No comments:

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...