设置 asp-items 而不获取 "the name does not exist in the current context" 的最简单示例

Simplest example for setting up asp-items without getting "the name does not exist in the current context"

我过去做过一些简单的网络编程,但现在我 return 尝试创建一个简单的单页应用程序,其中包含一个 "select" 在我的 cshtml 文件中,我无法超越“当前上下文中不存在该名称 ”错误。我选择使用 Visual Studio 来创建 .NET Core Razor(非 MVC)网络应用程序。我编码的所有内容都在两个文件中:Index.cshtml 和 Index.cshtml.cs,我试图保持简单,不实现任何控制器或使用 lambda 语法——实际上任何不是很简单的东西简单或简单——因为我的应用程序不需要它,而且我正试图限制我必须采用多少新技术来完成这个简单的应用程序。我想我了解模型绑定,因为当未定义 "select" 时,我已经在这两个文件中为我工作了。我已经能够绑定诸如您在下面看到的 machineSN 之类的东西。我正在尝试将 Index.cshtml.cs 文件中的字符串列表绑定到 Index.cshtml 文件中的 "select" 语句。

在Index.cshtml.cs ...

[BindProperties]
public class IndexModel : PageModel
{

public string machineSN = "123456789";
public string machineModel;
public List<SelectListItem> machineModels = new List<SelectListItem>
{
    new SelectListItem {Text="Unknown", Value="0"},
    new SelectListItem {Text="Omega", Value="1"),
}
:
:

在Index.cshtml ...

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<div class="text-left">
    <form enctype="multipart/form-data" method="post">
        Machine S/N: <input type="text" name="machineSN" asp-for="machineSN" />
        Model: <select name="machineModel" asp-for="machineModel" asp-items="machineModels"></select>
    </form>
</div>

当我将鼠标悬停在 Visual Studio 叠加在 cshtml 中 asp-items 字符串下的波浪形红线上时,我收到了错误消息。

我已经尝试为 asp-items 提供其他类型的东西——比如 SelectList 和 IEnumerable,但我仍然收到错误消息。如果可能的话,我更愿意看到只涉及 SelectListItems 的答案。我看到有人填写 "lists" 他们从数据库和 OnGet()s 中提供 asp 项的帖子但是你能告诉我如何在我上面列出的简单案例中做到这一点吗?非常感谢任何能使我找到简单解决方案的建议。我一直在浪费很多时间试图找出这个错误消息。

富有

你好像忘了输入Model.。您可以在 asp.net docs.

中查看如何使用 select 标签助手的示例

因此,在您的情况下,您需要将 select 更新为:

<select asp-for="machineModel" asp-items="Model.machineModels"></select>