在Razor视图中填充selectlistitem时,同步等待NULL参考异常

时间:2019-07-13 09:17:51

标签: asp.net-core dependency-injection async-await

我正在注入我的服务,以像这样在剃须刀中填充下拉列表

@inject Web.Services.MyService  Options

现在我正在尝试像这样填充我的下拉列表

<select asp-for="CityID" asp-items="await Options.GetCities();" class="form-control form-control-sm">
            <option>--Select--</option>
</select>

Gities方法在下面

public async Task<IEnumerable<SelectListItem>> GetCities()

        {   

            var cities = await _cityrepository.ListAllAsync();

            var items = new List<SelectListItem>
            {
                new SelectListItem() { Value = null, Text = "All", Selected = true }
            };
            foreach (SetupCities city in cities)
            {
                items.Add(new SelectListItem() { Value = city.CityId.ToString(), Text = city.Name});
            }

            return items;
        }

我遇到以下错误

NullReferenceException: Object reference not set to an instance of an object.
EvolvedX.Web.Services.VMWHService.GetCities() in VMWHService.cs
+
            var cities = await _cityrepository.ListAllAsync();
AspNetCore.Views_Warehouse_CreateWarehouse.ExecuteAsync() in CreateWarehouse.cshtml
+
        <select asp-for="CityID" asp-items="await Options.GetCities();" class="form-control form-control-sm">

我可以看到函数退出是第一个等待命中的getcities。什么是处理这种情况的正确方法 当发现等待导致我的selectlistitem为空时,M函数将在完成该方法之前退出。我想知道如何修改我的代码,以便将selectlistitem填充为空异常将得到解决

0 个答案:

没有答案