通过控制器操作填充下拉列表



我必须从List<string>填充dropdown list,其中键等于显示的值。我来提取值,进行了各种测试以连接到View,但没有成功。给定提取值的代码:

public async Task<IActionResult> PopulateDropDownList()
{
    try
    {
        var items = await DocumentDBRepository<CosmosDBTelemetry>.GetDeviceIds();
        List<string> deviceids = new List<string>();
        foreach(var item in items)
        {
            deviceids.Add(item.deviceId);
        }
        return View();
      }
      catch (Exception e)
      {
        throw (e);
     }
}

任何人都可以帮助我吗?

在模型视图控制器(MVC(框架中,将模型传递到视图是控制器的作业。假设您的字符串列表正确填充了items,则控制器需要将其传递到视图。

首先,您需要区分动作和辅助方法。动作是控制器类中的公共方法。用户可以通过URL访问操作,因此,在您的情况下,http://application_name/controller_name/populationRopdownlist将是一个有效的URL,尽管这对用户毫无意义。相反,您需要将PopulateDropDownList变成类似的辅助方法:

private async Task<IEnumerable<string>> GetDropdownOptionsList()
{
  List<string> items = ...;
  return items;
}

然后,通过URL动作(例如

(致电助手
public async Task<IActionResult> View()
{
  List<string> items = await GetDropdownListOptions();
  return View(items);
}

您可能希望查看此文档以获取有关控制器操作的信息。

第二,View()方法构建视图并将其发送给用户,但默认情况下,它不会传递数据。您可以通过调用View(items)而不是View()将字符串列表传递到视图。然后,您的观点看起来像:

@model IEnumerable<string>
<select>
  @foreach (string item in Model)
  {
    <option value="@item">@item</option>
  }
</select>

@model IEnumerable<string>指令指定视图期望将字符串列表传递到视图中。@foreach (string item in Model)通过列表中的每个字符串迭代并为每个字符串生成一个option元素。

如果您需要将多个数据模型传递到视图中,则可以使用ViewBagViewData对象。只需将ViewBag.Items = items;添加到您的PopulateDropDownList方法中:

private async void PopulateDropDownList()
{
  List<string> items = ...;
  ViewBag.Items = items;
}

然后您的视图看起来像:

<select>
  @foreach (string item in (IEnumerable<string>)ViewBag.Items)
  {
    <option value="@item">@item</option>
  }
</select>

我希望这会有所帮助!

您有两个选项。

选项1

从控制器中检索数据并从Razor页面访问。

mycontroller.cs

public async Task<IActionResult> PopulateDropDownList()
{
    var items = await 
                DocumentDBRepository<CosmosDBTelemetry>.GetDeviceIds();
                List<string> deviceids = new List<string>();
    foreach(var item in items)
    {
     deviceids.Add(item.deviceId);
    }
    ViewData["deviceids"] = deviceids;
    return View();
}

myviewpage.cshtml

<select>
        <option value="">Select an option</option>
      @foreach (string deviceid in ((List<string>)ViewData["deviceids"]))
      {
        <option value="@deviceid">@deviceid</option>
      }
    </select> 

选项2

直接从Razor页面检索和访问数据。

myviewpage.cshtml

@Code
    var items =  DocumentDBRepository<CosmosDBTelemetry>.GetDeviceIds();
    List<string> deviceids = new List<string>();
    foreach(var item in items)
     {
     deviceids.Add(item.deviceId);
     }
End Code
<select>
    <option value="">Select an option</option>
  @foreach (string deviceid in deviceids)
  {
    <option value="@deviceid">@deviceid</option>
  }
</select> 

最新更新