Search code examples
razorargumentnullexception

SelectList(Model.RoleDropDownDisp,"RoleId","RoleName") causes an ArgumentNullException: Value cannot be null. (Parameter 'items')


on post I have some error checking before saving and if true I return to Page()

In debugging I found out that it is a problem with my Drop Down Selection

    <div class="form-group">
        <label asp-for="WorkColUser.WorkColRoleId" class="control-label"></label>
    </div>
    <select id="RoleId" asp-for="RoleDropDownDisp" asp-items="@(new SelectList(Model.RoleDropDownDisp,"RoleId","RoleName"))">
        <option value="" selected disabled>@Localizer["--Choose Role--"]</option>
    </select>
    <div class="form-group">
        <input asp-for="WorkColUser.WorkColRoleId" readonly="readonly" class="form-control" />
        <span asp-validation-for="WorkColUser.WorkColRoleId" class="text-danger"></span>
    </div>

The problem is only if I have no error. Otherwise all is working fine.

my RoleDropDownDisp is defined as follows:

public IEnumerable<Role> RoleDropDownDisp { get; set; }

What can I do to avoid this error? Thanks for helping


Solution

  • I think you better take care of null case in your model but still a quick fix may be:

    @(new SelectList(Model?.RoleDropDownDisp ?? new List<Role>(),"RoleId","RoleName"))