Home > database >  Post data to MVC controller from DropDownList
Post data to MVC controller from DropDownList

Time:09-16

I have a MVC, multiple select DropDownList that populates the Select Items from a SelectListItem model.

@Html.DropDownList("EmployeeStatuses", (IEnumerable<SelectListItem>)ViewBag.EmployeeStatuses, new { multiple = "multiple", style = "width: 100%;", @class = "select2", onchange = "UpdateEmployeeStatusFilter()", id = "employee-status-type" })

When the user selects or unselects items from the DropDownList, I want to run a method in my controller that will filter the data in the view. This is done with the onChange event UpdateEmployeeStatusFilter().

<script type="text/javascript">
    function UpdateEmployeeStatusFilter() {
      var value = $('#employee-status-type').val();
      console.log(value);
      var a = ["X", "Y", "Z"];
      console.log(a);
      $.ajax({
        type: 'POST',
        url: '@Url.Action("SearchEmployee", "Employee")',
        data: { valueMember: value },
        dataType: 'json',
        traditional: true,
        success: function (msg) { alert(msg) }
    });

    };
  </script>

When I debug the script, I am able to get the value of value and write that to the console window. When the controller method is called, the value is null.

public IActionResult SearchEmployee(string itemsSelected)
{
    // Do Stuff with itemsSelected
    return RedirectToAction("Index");
}

My question is how do I get that value into my controller?

I am not sure if this code is relevant or not, but I will include it for clarity.

public IActionResult Index()
{
    // Get Employment Statuses
    IEnumerable<SelectListItem> statuses = _mockDataRepository.GetEmployeeStatuses().Select(c => new SelectListItem
    {
        Value = c.ValueMember,
        Text = c.DisplayMember,
        Selected = c.ValueMember == "AC"
    });
    ViewBag.EmployeeStatuses = statuses;
}
public class SelectListItem
{
    [Key]
    public string ValueMember { get; set; }
    public string DisplayMember { get; set; }
    public int SortOrder { get; set; } = 0;
}

CodePudding user response:

Name mismatch. The SearchEmployee() action method has itemsSelected input parameter. Therefore set the same parameter name in the .ajax call:

data: { itemsSelected: value }, 
  • Related