如何从 Razor Pages 中的 SelectList 项捕获 ID 值?

How to capture ID value from a SelectList item in Razor Pages?

我对一般的 Web 编程还很陌生,我正在尝试使用 ASP.Net Core 3.0 上的 Razor Pages 制作一个简单的数据输入页面。

我在使用标记中的 SelectList 时遇到了一些问题。我试图获得的行为是从视图中的 SelectList 捕获 ID 值,这只是拒绝正常工作,至少在 OnPost 方法上是这样。

这是我的代码:

Table Mapping

Get the records I need using FromSqlRaw

Main table and List of items as IEnumerable

Code in the View as SelectList

How the list looks on the actual site

我真正需要的是捕获列表项的 ID 值 (IDCON) 并将其 post 到 asp-for 中的绑定 属性,但不管怎样返回值始终为空的原因。关于我做错了什么或者可能是不同的方法有什么想法吗?

如有任何帮助,我们将不胜感激。

您可以尝试添加[BindProperty],这是一个使用假数据的工作演示。

cshtml:

<form method="post">
    <label asp-for="registro.IDCON">Consecuencia</label>
    <select asp-for="registro.IDCON" asp-items="@(new SelectList(Model.consecuencias,"IDCON","DSCCON"))">
        <option value="">---Elegir Consecuencia---</option>
    </select>
    <span asp-validation-for="registro.IDCON" class="text-danger"></span>
    <input type="submit" value="submit"/>
</form>

cshtml.cs:

public class TestIDCONModel : PageModel
    {
        [BindProperty]
        public ROCONSEC registro { get; set; }
        [BindProperty]
        public List<ROCONSEC> consecuencias { get; set; }
        public IActionResult OnGet()
        {
            consecuencias = new List<ROCONSEC> { new ROCONSEC { IDCON = 1, DSCCON = "PROCESO RALENTIZADO" }, new ROCONSEC { IDCON = 2, DSCCON = "PROCESO DESTRUIDO" } };
            return Page();
        }
        public IActionResult OnPost()
        {
            int IDCON = registro.IDCON;
            return Page();
        }
    }

结果:

感谢您的回答。

很尴尬地说我遇到这个问题是因为我在外键值上不正确地映射了我的主要 table 模型。我直接映射为相应 table 的对象而不是字段类型,它在运行时试图从我的主 table 获取 ID,这显然不存在。

也就是说,是您的贡献让我意识到了这一点,当我使用 Request.Form[""] 检查是否有任何值从视图传递到 VM 时,这让我印象深刻因为它很奇怪,但是 ModelState 中的 acceptedValue 为空。我重新检查了我的整个代码并最终更正了这个问题,现在我的页面可以正常工作了。

干杯!