ASP.NET MVC - drop-down list - partial views and model binding

I am new to ASP.NET MVC and trying to find a better way to do this. It's probably simple, but I just want to do it right, so I thought I would ask.

Let's say I have a model that is this:

Task - Id, Description, AssignedStaffMember

StaffMember - Id, FirstName, LastName

and, in my opinion, I want to create a new task. I am doing a strongly typed Razor view and can use EditorFor to create text fields for the description, but what about AssignedStaffMember?

I want a drop-down list of all current employees and I can choose one, then it will be passed to the action method, which NewTask(string description, StaffMember assignedStaffMember) either, or I could have an int for staffId instead of the StaffMember object and look for it in the action method.

What is the best way to do this? I need to go into the database to get a list from the staff, so here is what I thought:

  • Take a partial view to expand the list of employees, which will be used several times and use @Html.Action("ListStaff", "Staff") to call it. Then the action method has

     public ActionResult ListStaff() { IEnumerable<StaffMember> model = _serviceLayer.GetAllStaff(); return PartialView(model); } 

    However, I'm not sure how this will work with model binding, I understand that it must have the correct name for the form in order to submit it, would I need to pass the name of the partial view in order to put on the element that I am assuming?

  • Instead of calling the dispatcher to get staff, create a ViewModel that contains my Task and IEnumerable. maybe send this information in partial view.

  • Html helper?

  • Can I use EditorFor somehow?

which one (or more) will be better? and how would I make model binding?

+5
asp.net-mvc razor model-binding partial-views
Mar 04 2018-11-11T00:
source share
1 answer

Here is one way to do it. Create TaskDetailsViewModel

 public class TaskDetailsViewModel { public TaskDetailsViewModel() { this.Task = new Task(); this.StaffMembers = new List<StaffMember>(); } public Task Task { get; set; } public IEnumerable<StaffMember> StaffMembers { get; set; } } 

In the controller

 public ActionResult Edit(int id) { var task = taskRepository.GetTaskByID(id); var taskDetailsViewModel = new TaskDetailsViewModel(); // Populate taskDetailsViewModel from task and staff return View(taskDetailsViewModel); } [HttpPost] public ActionResult Edit(TaskDetailsViewModel taskDetailsViewModel) { if (ModelState.IsValid) { taskRepository.Save(taskDetailsViewModel.Task); } else { // Show Error } return View(taskDetailsViewModel); } 

In view (strongly tied to TaskDetailsViewModel)

 @Html.DropDownListFor(model => model.Task.AssignedStaffMember, new SelectList(Model.StaffMembers, "ID", "FirstName", Model.Task.AssignedStaffMember)) @Html.ValidationMessageFor(model => model.Task.AssignedStaffMember) 
+17
Mar 04 2018-11-11T00:
source share



All Articles