2

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;
}

1 Answer 1

1

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

data: { itemsSelected: value }, 
Sign up to request clarification or add additional context in comments.

1 Comment

Ugg, that was the issue. The least you could have done is made it look a little more difficult! Just as a note for others, since the values are in an Array, I had to change the line var value = $('#employee-status-type').val(); to var value = new Array($('#employee-status-type').val());

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.