0
votes

I'm working on a form to manipulate user/employee data in my application.

I have a simple drop-down select tag helper (followed by a label to output the current value) to change the employee's Regional Sales Manager assignment:

<select asp-for="Employee.RegionalSalesManager" asp-items="Model.RegionalSalesManagers" disabled="@(Model.EmployeeRole == 1 ? null : "disabled")">
    <option value="0">Select...</option>
</select>
<label id="lblRegionalSalesManagerID">@((Model.Employee != null) ? Model.Employee.RegionalSalesManager.ToString() : @"")</label>

This works fine upon initially loading the Model.Empolyee from the database; in the view, the select tag (drop-down menu) shows the correct item (Regional Sales Manager) and the matching value is output in the label:

Good Drop-Down Menu

Another part of the form allows changing the employee's Role - based on the Role, the Regional Sales Manager assignment may not be necessary. When the employee Role is changed, the form posts and if the Regional Sales Manager assignment is not necessary, the Model.Employee.RegionalSalesManger value is zeroed:

[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Index(UserManagementViewModel model)
{
    if (model.Employee != null)
    {
        switch (model.EmployeeRole)
        {
            case 2: // employee Role is Regional Sales Manager
                model.Employee.RegionalSalesManager = 0; // no need for assignment
                break;
        }
    }
    return View(await BuildModel(model));
}

Upon view refresh, the logic in the select tag helper disabled="@(Model.EmployeeRole == 1 ? null : "disabled") kicks in and disables the menu appropriately, and the label shows the value was indeed successfully zeroed; however, the menu still shows the last selection when my expectation is that it would show item "Select...", since that is the item that corresponds to value zero:

Unexpected Drop-Down Menu

Posting back one more time (by changing the Role to another that does not require a Regional Sales Manager assignment) does end up setting the menu item to "Select..."

What am I missing here? The view model is being returned with the expected value after the first post-back; why doesn't the menu selection get updated?

1
Maybe the same issue I've had with normal MVC where the model state is not being reset? I have quite a few ModelState.Clear hacks laying about because of that. Not sure Core has the same weirdness...Nikki9696

1 Answers

0
votes

I figured it out. The posted value for the select tag helper, when the form is submitted, "overrides" (read "sets") the value on the model. You can't update the model value in the POST controller and expect the select tag helper to use the new value.