c# - 带有 ViewBag 的 DropDownListFor 不传递值
问题描述
我想通过创建视图传递新的预订,用户可以在其中选择不同的位置。我可以在视图中选择位置,但位置属性仍设置为 null,当我单击提交时,其他一切正常。
位置存储在基础结构模型中的列表中,我猜,问题是,我的值是 LocationIds 而不是 Location 对象,但我不知道如何使用对象值创建选定列表,因为所有示例带有 ID/名称。
这些是我的模型:
public class Infrastructure
{
public int InfrastructureId { get; set; }
[Required]
public List<Location> Locations { get; set; }
}
public class Location
{
public int LocationId { get; set; }
public Address Address { get; set; }
public int CountEmployee { get; set; }
public GPS Coordinates { get; set; }
public List<ChargingStation> ChargingStations { get; set; }
}
这是控制器中的创建:
public IActionResult Create()
{
Infrastructure infrastructure = _infrastructure.GetRealInfrastructure();
List<Location> locations = infrastructure.Locations;
ViewBag.Locations = new SelectList(locations, "LocationId", "Address.City");
return View();
}
这是视图:
<div class="form-group">
<label asp-for="end" class="control-label"></label>
<input asp-for="end" class="form-control" id="endTime"/>
<span asp-validation-for="end" class="text-danger"></span>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label asp-for="location" class="control-label"></label>
@Html.DropDownListFor(model => model.location, (IEnumerable<SelectListItem>)ViewBag.Locations, "Choose Location", new { @class = "form-control" })
<span asp-validation-for="location" class="text-danger"></span>
</div>
</div>
例如 endtime 的值已保存,但位置仍然设置为空,所以我猜我缺少一些选择/提交标签?还是如前所述,因为我传递了一个字符串值(LocationId)而不是实际的位置对象?
解决方案
推荐阅读
- matlab - 在 Octave 中调用向量化操作以获得多个输出
- javascript - 如何在VSCODE中将反斜杠更改为前斜杠?
- javascript - pm2 文件夹路径和多个运行脚本
- julia - 朱莉娅有克罗内克三角洲吗?
- python - 如何在随机选择函数中读取包含两列的行文件
- apache-nifi - 如何在 nifi 中为 csv 文件生成 Avro 模式
- powershell - PowerShell Studio exe不会在打包的exe中按下按钮时启动新的Windows窗体
- azure-ad-b2c - MSAL / MS Graph 代码适用于 .Net Core 3.1,但不适用于 .Net Framework 4.8
- node.js - 在 Nodejs 无状态下通过 twitter 进行身份验证
- python - 使用 Python docx 库阅读导航标题