0

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; }
}
2
  • Is that Department property has enum type in viewmodel class? If you want to display concatenated text value, I think you should try DropDownListFor instead. Commented Dec 17, 2018 at 6:49
  • @TetsuyaYamamoto I am not sure what to choose to display, that is why I ask this question too. Commented Dec 17, 2018 at 7:08

1 Answer 1

3

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);
} 
Sign up to request clarification or add additional context in comments.

13 Comments

Almost true, just it is not posting the department id that we choose into database.
Please explain the problem somewhat further. I shall fix!
Edited your answer as a working version and added user class at my question. All is fine except database did not receive 1 value as a departmentid when I create the user and post the value.
No, sorry, misunderstanding happen. Still posting the departmentid is not working. Rest is okey.
Can you give me remote access please!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.