如何在创建页面上从模型集合中填充下拉列表

本文关键字:集合 模型 填充 下拉列表 创建 | 更新日期: 2023-09-27 18:09:08

我相信这是我错过的一件简单的事情。我试图添加一个下拉列表的创建。CSHTML,目的是从数据库填充列表。为了这个实验,我搞砸了以下内容:两个类对应于有值的数据库表。

namespace MvcTestApplication.Models
{
public class Complaints
{
    public int ID { get; set; }
    public string User { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string  Nature { get; set; }
    public string Month { get; set; }
    public string Year { get; set; }
    public string Account { get; set; }
    public string Employee { get; set; }
    public string Manager { get; set; }
    public int CompanyID { get; set; }
    public int CompanyNumID { get; set; }
    public int DepartmentID { get; set; }
    public int ClientID { get; set; }
    public int ClientCodeID { get; set; }
    public string Source { get; set; }
    public string Status { get; set; }
    public virtual ICollection<Company> Companies{ get; set; }
}
namespace MvcTestApplication.Models
{
public class Company
{
    public int CompanyID { get; set; }
    public string CompanyName { get; set; }
    public bool enabled { get; set; }
}
}

则DAL

namespace MvcTestApplication.DAL
{
public class ComplaintDBContext : DbContext
{
    public DbSet<Complaints> Complaints { get; set; }
}

在create。cshtml页面,我只是希望能够填充与公司的下拉列表(许多更多的下拉列表后,我得到这个工作),但到目前为止,我总是得到一个空引用,每当我尝试。在create actionresult上,我尝试传递一个新的投诉模型,只是投诉模型,我错过了如何使公司集合被填充。

 <div class="editor-label">
        @Html.LabelFor(model => model.ReleaseDate)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ReleaseDate, new { id = "release_date" })
        @Html.ValidationMessageFor(model => model.ReleaseDate)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Source)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Source)
        @Html.ValidationMessageFor(model => model.Source)
    </div>
  <div class="editor-label">
        @Html.LabelFor(model => model.CompanyID)
    </div>
    <div class="editor-field">
    @Html.DropDownListFor(model => model.CompanyID , new SelectList(Model.Companies , "CompanyID", "CompanyName"), "-- Select Company--")
        @Html.ValidationMessageFor(model => model.CompanyID)
    </div>

如何在创建页面上从模型集合中填充下拉列表

我认为您需要为您的复杂对象类型构建一个模板。类似这样的内容应该可以让您开始为投诉定义自定义编辑器模板。这将自动为投诉集合中的每个元素呈现。

您需要将其存储在~/Views/Shared/EditorTemplates/complain .cshtml:

@model Complaints
<div>
    @Html.LabelFor(x => x.id): 
    @Html.EditorFor(x => x.id)
    @Html.LabelFor(x => x.Nature): 
    @Html.EditorFor(x => x.Nature)
    @Html.LabelFor(x => x.ReleaseDate): 
    @Html.EditorFor(x => x.ReleaseDate)
    @Html.LabelFor(x => x.Source): 
    @Html.EditorFor(x => x.Source)
    @Html.LabelFor(x => x.Status): 
    @Html.EditorFor(x => x.Status)
</div>

给我们,只需写:

@Html.EditorFor(model => model.Complaints)