【发布时间】:2020-11-03 20:00:25
【问题描述】:
我正在尝试按照here 显示的示例进行操作。这是一个简单的选择(组合框)。
这是我的模型的代码:
public class TestHarnessViewModel
{
public TestHarnessViewModel(IConfiguration configuration)
{
var hostname = ApiGateway.GetApiGatewayHost();
var apiContext = configuration["AppSettings:TestHarnessApiContext"];
var localHostname = $"localhost:{configuration["AppSettings:TestHarnessServicePort"]}";
HostTypes = new List<SelectListItem>
{
new SelectListItem {Value = localHostname, Text = "locally hosted"},
new SelectListItem {Value = $"{hostname}/{apiContext}", Text = "API Gateway"}
};
HostName = localHostname;
}
public string HostName { get; set; }
public List<SelectListItem> HostTypes { get; }
}
这是我认为的代码:
@model TestHarnessViewModel
<div class="row">
<div class="col-md-12"></div>
<select asp-for="HostName" asp-items="Model.HostTypes"></select>
</div>
在控制器中,我在构造函数中创建了TestHarnessViewModel 的实例并将其设置为类级别变量(称为model)。然后我将它传递到需要的视图中。 (Return View(model) 或 Return View("Index", model))
这似乎在 UI 上运行良好。我得到一个带有两个选项的选择框,我可以选择一个。但是当我尝试在控制器中引用model.HostName 时,HostName 始终为空。 (或者当我在代码中默认值时,它保持默认值。)
我读到我可能需要在HostName 上添加[BindProperty]。但我试过了,它对结果没有任何影响(它保持为空/默认值。)
如何将用户在 UI 中选择的值设置为模型?(在我的示例中,属性名为 HostName)
【问题讨论】:
标签: c# asp.net-core asp.net-core-mvc asp.net-core-3.1