来自Razor的页面清除模型值-何时不应该?

问题描述 投票:0回答:1

我有一个简单的单页ASP.NET Core Razor应用程序,该应用程序中包含一个要从Model变量中填充的“ select”。在我使用OnPost()方法检查它们时,将清除Model变量中的值。 (名为machineModel的变量返回的很好,但是Post中清除了Model中名为machineModels的变量。)这是怎么做的?

这是Index.cshtml的样子:

@page
@model IndexModel
@{
   ViewData["Title"] = "Home page";
}
<div class="text-left">
<form enctype="multipart/form-data" method="post">
   Model: <select name="machineModel" asp-for="machineModel" asp-items="Model.machineModels" required></select>
   <input type="submit" asp-page-handler="Download" value="Download certificate" />
</form>
</div>

这是Index.cshtml.cs的样子:

[BindProperties]
public class IndexModel : PageModel
{
   public string machineModel { get; set; }
   public List<SelectListItem> machineModels = new List<SelectListItem>();

   // In some other function in the class the machineModels variable is filled (several times) ...

   string modelStr = reader.GetAttribute("value");
   int numMachineModels = machineModels.Count;
   string machineModelIndexStr = numMachineModels.ToString();   
   machineModels.Add(new SelectListItem { Text = modelStr, Value = machineModelIndexStr, Selected = true });

   // And here's the Post method ...

   public IActionResult OnPostDownload()
   {
      // Doesn't matter what's in here, machineModels is already cleared at this point

      return Page();
   }
}

感谢您提供的任何帮助,丰富

c# asp.net-core razor html-select
1个回答
0
投票

绑定不适用于字段,请尝试像属性一样声明machineModels并通过SelectListItem的新列表对其进行初始化

© www.soinside.com 2019 - 2024. All rights reserved.