.NET MVC Core Json / Async Task填充SelectList / IEnumerable

时间:2017-03-12 17:47:58

标签: c# .net json asp.net-core-mvc selectlist

我无法找到答案,也无法通过从MVC WepApi获取Json数据并将其发送到下拉列表来解决我的问题。

我收到以下错误:

  

RuntimeBinderException:“Microsoft.AspNetCore.Mvc.Rendering.SelectList.SelectList(System.Collections.IEnumerable,string,string)”的最佳重载方法匹配具有一些无效参数

我使用以下代码获取Json数据,此代码现在位于Controlller中:

    public async Task<IActionResult> GrabEmployees()
    {
        var item = new List<EmployeeViewModel>();

        using (var employee = new HttpClient())
        {
            employee.BaseAddress = new Uri("http://localhost:5050/");
            employee.DefaultRequestHeaders.Accept.Clear();
            employee.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await employee.GetAsync("api/employees");
            if (response.IsSuccessStatusCode)
            {
                item = await response.Content.ReadAsAsync<List<EmployeeViewModel>>();
            }
        }
        return ViewBag.Employees = item.Select(employee => new SelectListItem { Value = employee.EmployeeNumber, Text = (employee.FirstName + " " + employee.LastName) });
    }

所以使用上面的代码我尝试将Task设置为一个字符串,IEnumerable,JsonResult,各种各样的东西它给了我同样的错误。这让我相信问题可能是因为它是异步的。我不知道,我是Json和MVC Core的新手。

以下是我将信息传递给视图的方法:

    public IActionResult Assignments()
    {
        ViewData["Title"] = "Assign Asset";
        ViewData["Message"] = "Use this section to assign assets to Employees.";
        ViewBag.Employees = GrabEmployees();
        ViewBag.Assets = AManger.GetAll();
        //Allows to assign assets to employees
        return View();
    }

以下是查看页面代码:

@model IEnumerable<Final.HRInventoryApp.Models.AssetViewModel>

<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>
@using (Html.BeginForm())
{
    @Html.DropDownList("Asset", new SelectList(ViewBag.Assets, "Id", "TagNumber"))
    @Html.DropDownList("EmployeeId", new SelectList(ViewBag.Employees, "Value", "Text"))
    <input type="submit" id="buttonsubmit" value="Submit" />

}

我的结果好坏参半。当我第一次启动应用程序时,页面加载并填充下拉列表。如果我点击另一个页面然后返回到所述页面,它将完全失败并显示该错误。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您的GrabEmployees方法看起来正在返回一个IActionResult,您正在使用其他操作方法将其设置为viewbag!你在那个方法中也有一个声明return ViewBag.Employees;!这看起来不正确。您应该考虑更新GrabEmployees方法以返回所需的数据(SelectListItem项的集合)

public async Task<IEnumerable<SelectListItem>> GrabEmployees()
{
    var item = new List<SelectListItem>();

    using (var employee = new HttpClient())
    {
        employee.BaseAddress = new Uri("yourUrlForApiEndpointHere");
        employee.DefaultRequestHeaders.Accept.Clear();
        employee.DefaultRequestHeaders.Accept

                            .Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await employee.GetAsync("api/employees");
        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsAsync<List<EmployeeViewModel>>();
            return data.Select(x => new SelectListItem { Value = x.EmployeeNumber,
                                           Text = (x.FirstName + " " + x.LastName) });
        }
    }
    return item;
}

在您的其他操作方法中,调用此方法并将其传递给view。

public  async Task<IActionResult> Assignments()
{
    ViewData["Title"] = "Assign Asset";
    ViewData["Message"] = "Use this section to assign assets to Employees.";
    var d =  await GrabEmployees();
    ViewBag.Employees = d.ToList();
    // to do : Fix Assets the same way
    return View();
}

现在在视图中,

@Html.DropDownList("EmployeeId", ViewBag.Employees as List<SelectListItem>)