Alper
Alper

Reputation: 495

Populating DropDownList in ASP.NET MVC

Following code is to create users. I have a user class, I need to create users here. But I have department id's on a person and that department id refers to another table in the database whose name is Department.

public ActionResult Create()
{
    // disable lazy because of error it creates
    _db.Configuration.LazyLoadingEnabled = false;
    var data = _db.Departments.OrderBy(a => a.DepartmentId).ToList();
    ViewData["DepartmentList"] = data;

    return View();
}

Here is View:

@{
    var departmentLists = ViewData["DepartmentList"]; // Cast the list
}

<div class="form-group">
     @Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
          @Html.EnumDropDownListFor(model => model.Department, htmlAttributes: new { @class = "form-control" })
         @Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })
     </div>
</div>

This model.department part is the where i lost. I need to list my department in order of the list, when user select, i want to select the id of the department. Like this;

enter image description here

So I want the user to see

Department Name + SubDepartment name

and when they choose from the list, the chosen thing is

departmentid

so I can add in the database like that.

Here is my Create Post method:

public ActionResult Create([Bind(Include = "ID,LastName,FirstMidName,EnrollmentDate,Email,Department,Position,Active")] User user)
{
    if (ModelState.IsValid)
    {
        _db.Users.Add(user);
        _db.SaveChanges();
        return RedirectToAction("Index");
    }

     return View(user);
 }

Her is my User class;

public class User
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int DepartmentId { get; set; }

    // Other fields removed for brevity
}

Here is Department class;

public class Department
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DepartmentId { get; set; }

    public string DepartmentName { get; set; }

    public string SubDepartmentName { get; set; }
}

Upvotes: 0

Views: 124

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32069

Write your Create GET method as follows:

public ActionResult Create()
{
    // disable lazy because of error it creates
    _db.Configuration.LazyLoadingEnabled = false;

    var departmentList = _db.Departments.Select(d => new
     {
        d.DepartmentId,
        DepartmentName = d.DepartmentName + " " + d.SubDepartmentName
     }).OrderBy(a => a.DepartmentId).ToList();

    ViewBag.DepartmentList = new SelectList(departmentList,"DepartmentId","DepartmentName");

    return View();
}

Then in the view:

<div class="form-group">
        @Html.LabelFor(model => model.DepartmentId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("DepartmentId", ViewBag.DepartmentList as SelectList, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.DepartmentId, "", new { @class = "text-danger" })
        </div>
    </div>

Another problem is in your Create POST method. You are not allowing you DepartmentId to pass in your Bind include list. Please update you Create POST method as follows:

public ActionResult Create([Bind(Include = "ID,LastName,FirstMidName,EnrollmentDate,Email,DepartmentId,Position,Active")] User user)
{
    if (ModelState.IsValid)
    {
       _db.Users.Add(user);
       _db.SaveChanges();
       return RedirectToAction("Index");
    }

    return View(user);
} 

Upvotes: 3

Related Questions