首页 > 解决方案 > 带有 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)而不是实际的位置对象?

标签: c#asp.net-mvc

解决方案


推荐阅读