Wednesday, March 19, 2014

How To Create a Dynamic DropdownList in ASP.NET MVC5 Step by Step

Dynamic DropdownList in ASP.NET MVC5 Step By Step

Create Two DB Tables e.g.

1.Designstions
Colunns: DesignationID(PK,FK,numeric(6,0),not null)
                Designation (Varchar(50),null)


2.Persons
Columns: PersonID(PK,numeric(6,0),not null)
                 DesignationID(FK,numeric(6,0),not null)


Create The Models:

Designation.cs

{

   public decimal DesignationID { get; set; }
    public string Designation { get; set; }

}

Person.cs

{

 
    public decimal PersonID{ get; set; }
     [DisplayName("Designation")]
   public decimal DesignationID{ get; set; }
 
   public virtual  Designation designation { get; set; }

 

PersonController.cs

{

  public class PersonController: Controller

{

     public ActionResult Index()
        {
            var  mamun= db.Persons.Include(t => t.designation );
            return View(mamun.ToList());
        }


 public ActionResult Create()
        {

          ViewBag.DesignstionID= new SelectList(db.Designstions, "DesignstionID", "Designstion");
            return View();
        }

  public ActionResult Edit(decimal id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Person person = db.Persons.Find(id);
            if (tblsalesperson == null)
            {
                return HttpNotFound();
            }
         ViewBag.DesignstionID= new SelectList(db.Designstions, "DesignstionID", "Designstion",person.DesignstionID);
                   return View(person);
        }

}

}

Create.cshtml & Edit.cshtml:

<div class="form-group">
                @Html.Label("Designation", new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("
DesignstionID")
                    @Html.ValidationMessageFor(model => model.
DesignstionID)
                </div>
            </div>

To Add CSS class  'dropdownList' ,Use:

@Html.DropDownList("DesignstionID", (IEnumerable<SelectListItem>)ViewBag.DesignstionID, new { @class = "dropdownList" })  Instead Of that.


Index: 

 @foreach (var item in Model) 

{

    <td>
                    @Html.DisplayFor(modelItem => item.
Designation.Designation)      
  </td

To Get a Fanstatic One: