Listbox for MVC 6 EF 7 Property not Populating

送分小仙女□ 提交于 2019-12-02 07:00:00

Change Create() method in ChildrenController, change

    public IActionResult Create()
    {
        ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Parent");
        return View();
    }

to

    public IActionResult Create()
    {
        ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Name");
        return View();
    }

In Create.cshtml, change

<select asp-for="ParentId" class="form-control"></select>

to

@Html.DropDownList("ParentId", null, htmlAttributes: new { @class = "form-control" })

The generated code is incorrect, it is a bug https://github.com/aspnet/Scaffolding/issues/149

One solution using "tag helpers" is:

Controller

...
ViewData["Parents"] = new SelectList(_context.Set<Parent>(), "ParentId", "Name", child.ParentId);
...

View

@{
    var parents = (IEnumerable<SelectListItem>)ViewData["Parents"];
}
...
<select asp-for="ParentId" asp-items="parents" class ="form-control">
     <option disabled selected>--- SELECT ---</option>
</select>
...

Here's how to do it when there is only one type of object which is nested within another object of the same type.

Object:

public class Fleet
{

    public int Id { get; set; }
    public Fleet ParentFleet { get; set; }
    public int? ParentFleetId { get; set; }

    public string Name { get; set; }

    [InverseProperty("ParentFleet")]
    public virtual List<Fleet> Children { get; set; }

    public List<UserFleet> UserFleets { get; set; }
}

Controller:

ViewData["ParentFleetId"] = new SelectList(_context.Set<Fleet>(), "Id", "Name");
return View();

View:

<form asp-action="Create">
    <div class="form-horizontal">
        <h4>Fleet</h4>
        <hr />
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Name" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger" />
            </div>
        </div>
        <div class="form-group">
            <label asp-for="ParentFleet" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="ParentFleetId" asp-items="ViewBag.ParentFleetId" class="form-control">
                    <option value=""></option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!