MVC 6 EF 7屬性的列錶框未填充

asp.net-core-mvc asp.net-mvc-scaffolding entity-framework-core

我已經嘗試了一段時間來填充列錶框,我似乎無法弄明白。我已經非常廣泛地研究了實體框架7文檔,但我還是新手。 MVC6 / EF7還沒有很多教程,所以很難知道將一個實體類與另一個實體類相關聯的最佳實踐是什麼。請原諒問題的長度,我只是想徹底解決。

我正在使用實體框架7,asp.net 5和MVC 6。

重現問題的步驟

  1. 創建一個新的ASP.Net Web應用程序 →項目名稱: ListBox.Web →解決方案ListBox的名稱
  2. 選擇APS.NET 5模板Web應用程序
  3. Models文件夾中創建兩個類

    Parent.cs

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace ListBox.Web.Models
    {
        public class Parent
        {
            public int ParentId { get; set; }
            [Required]
            public string Name { get; set; }
            public ICollection<Child> Children { get; set; }
        }
    }
    

    Child.cs

    using System.ComponentModel.DataAnnotations;
    
    namespace ListBox.Web.Models
    {
        public class Child
        {
            public int ChildId { get; set; }
            [Required]
            public string Name { get; set; }
            public int ParentId { get; set; }
            public Parent Parent { get; set; }
        }
    }
    
  4. 使用scaffolding為每個數據類創建控制器和視圖腳手架控制器

  5. _Layout.cshtml添加指向控制器的_Layout.cshtml

                <ul class="nav navbar-nav">
                    <li><a asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-controller="Parents" asp-action="Index">Parents</a></li>
                    <li><a asp-controller="Children" asp-action="Index">Children</a></li>
                    <li><a asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
    
  6. 創建數據庫

    ListBox\src\ListBox.Web>dns ef migrations add Initial
    ListBox\src\ListBox.Web>dnx ef database update     
    
  7. 運行Web應用程序

  8. 添加幾個父母。

    在此處輸入圖像描述

  9. 嘗試添加孩子。

    • 顯示父母的下拉框,但下拉框中沒有項目可供選擇
    • 在此處輸入圖像描述
    • 列錶框的HTML是: <select class="form-control" data-val="true" data-val-required="The ParentId field is required." id="ParentId" name="ParentId"></select>

控制器源代碼

using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using ListBox.Web.Models;

namespace ListBox.Web.Controllers
{
    public class ChildrenController : Controller
    {
        private ApplicationDbContext _context;

        public ChildrenController(ApplicationDbContext context)
        {
            _context = context;    
        }

        // GET: Children
        public IActionResult Index()
        {
            var applicationDbContext = _context.Child.Include(c => c.Parent);
            return View(applicationDbContext.ToList());
        }

        // GET: Children/Details/5
        public IActionResult Details(int? id)
        {
            if (id == null)
            {
                return HttpNotFound();
            }

            Child child = _context.Child.Single(m => m.ChildId == id);
            if (child == null)
            {
                return HttpNotFound();
            }

            return View(child);
        }

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

        // POST: Children/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Child child)
        {
            if (ModelState.IsValid)
            {
                _context.Child.Add(child);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Parent", child.ParentId);
            return View(child);
        }

        // GET: Children/Edit/5
        public IActionResult Edit(int? id)
        {
            if (id == null)
            {
                return HttpNotFound();
            }

            Child child = _context.Child.Single(m => m.ChildId == id);
            if (child == null)
            {
                return HttpNotFound();
            }
            ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Parent", child.ParentId);
            return View(child);
        }

        // POST: Children/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(Child child)
        {
            if (ModelState.IsValid)
            {
                _context.Update(child);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Parent", child.ParentId);
            return View(child);
        }

        // GET: Children/Delete/5
        [ActionName("Delete")]
        public IActionResult Delete(int? id)
        {
            if (id == null)
            {
                return HttpNotFound();
            }

            Child child = _context.Child.Single(m => m.ChildId == id);
            if (child == null)
            {
                return HttpNotFound();
            }

            return View(child);
        }

        // POST: Children/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(int id)
        {
            Child child = _context.Child.Single(m => m.ChildId == id);
            _context.Child.Remove(child);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}

子Create.cshtml

@model ListBox.Web.Models.Child

@{
    ViewData["Title"] = "Create";
}

<h2>Create</h2>

<form asp-action="Create">
    <div class="form-horizontal">
        <h4>Child</h4>
        <hr />
        <div asp-validation-summary="ValidationSummary.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="ParentId" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="ParentId" class ="form-control"></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>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}

一般承認的答案

ChildrenController更改Create()方法,進行更改

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

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

Create.cshtml ,更改

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

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

熱門答案

生成的代碼不正確,這是一個錯誤https://github.com/aspnet/Scaffolding/issues/149

使用“標籤助手”的一種解決方案是:

調節器

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

視圖

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



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因