How to pass the selected value of DropdownListFor of a list of view model from view to controller

  Kiến thức lập trình

Here’s my viewmodel:

namespace Project.ViewModels.Plan
{
    public class PlanTaskViewModel : IEquatable<PlanTaskViewModel>
    {
        [DisplayName("Priority")]
        public string Priority { get; set; }
        public List<string> Priorities = new List<string> { "P1", "P2", "P3", "P4"};
    }
}

Here’s my view:

@model IEnumerable<PlanTaskViewModel>
@using (Html.BeginForm(PlanControllerActionNames.AddTask,
    PlanControllerActionNames.ControllerName,
    FormMethod.Post,
    new { id = "form-add-plan-tasks" }
    ))
{
    <table id="table-create-plan-tasks" class="table">
        <thead>
            <tr>
                <th>@Html.DisplayNameFor(model => model.Priority)</th>
            </tr>
        </thead>
        <tbody>
            @{var models = Model.ToList();}
            @for (int i=0;i<models.Count;i++)
            {
                <tr>
                    <td>
                        @{
                            @Html.DropDownListFor(m => models[i].Priority, models[i].Priorities.Select(e => new SelectListItem
                            {
                                Text = e,
                                Value = e,
                                Selected = e == "P3"
                            }), new
                            {
                                Name = "Priorities"
                            })
                        }
                    </td>
                </tr>
            }
        </tbody>
    </table>
}

Here’ my controller:

[HttpPost]
public ActionResult AddTask(List<PlanTaskViewModel> models)
{
    ...
}

I want to get the user’s selected priority value of each “PlanTaskViewModel” in my controller. How to make the user’s selected priority value of each “PlanTaskViewModel” be passed from view to controller without jquery?

I get null “models” in my “AddTask” controller.

New contributor

user22606962 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT