简体   繁体   English

c# MVC 实体框架 - 仅显示正确的子记录

[英]c# MVC Entity Framework - Show only correct child records

I'm new to MVC and Entity framework and i am building my first web app with those 2 technologies.我是 MVC 和实体框架的新手,我正在使用这两种技术构建我的第一个 Web 应用程序。 I am following a great tutorial (database first) and i have my basic application working now.我正在学习一个很棒的教程(首先是数据库),现在我的基本应用程序正在运行。 But there is something the tutorial doesn't talk about.但是有一些教程没有讨论。

Let's take this scenario: I have 3 tables: Cars, Manufacturers, Models.让我们假设这个场景:我有 3 个表:汽车、制造商、模型。

When i go to the auto generated view for create a new car, i have the correct dropdowns to enter the manufacturer and the model.当我转到自动生成的视图以创建新车时,我有正确的下拉菜单来输入制造商和型号。 But the dropdown with the models list is showing all the models and not just the ones related to the manufacturer i chose.但是带有模型列表的下拉列表显示了所有模型,而不仅仅是与我选择的制造商相关的模型。

MODELS楷模

Models楷模

using System;
using System.Collections.Generic;

public partial class model
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public model()
    {
        this.cars = new HashSet<car>();
        this.versions = new HashSet<version>();
    }

    public int id { get; set; }
    public string name { get; set; }
    public Nullable<int> manufacturerId { get; set; }
    public bool active { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<car> cars { get; set; }
    public virtual manufacturer manufacturer { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<version> versions { get; set; }
}

Manufacturers制造商

using System;
using System.Collections.Generic;

public partial class manufacturer
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public manufacturer()
    {
        this.cars = new HashSet<car>();
        this.models = new HashSet<model>();
    }

    public int id { get; set; }
    public string name { get; set; }
    public bool active { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<car> cars { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<model> models { get; set; }
}

Cars汽车

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class car
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public car()
    {
        this.carimages = new HashSet<carimage>();
    }

    public int id { get; set; }
    [Display(Name = "#")]
    public Nullable<int> bodytypeId { get; set; }
    [Display(Name = "Body Type")]
    public Nullable<int> manufacturerId { get; set; }
    [Display(Name = "Model")]
    public Nullable<int> modelId { get; set; }
    [Display(Name = "Version")]
    public Nullable<int> versionId { get; set; }
    [Display(Name = "Fuel")]
    public Nullable<int> fuelId { get; set; }
    [Display(Name = "Transmission")]
    public Nullable<int> transmissionId { get; set; }
    [Display(Name = "Color")]
    public Nullable<int> colorId { get; set; }
    [Display(Name = "HP")]
    public Nullable<int> horsePower { get; set; }
    [Display(Name = "KW")]
    public Nullable<int> kw { get; set; }
    [Display(Name = "CC")]
    public Nullable<int> cc { get; set; }
    [Display(Name = "CO2")]
    public Nullable<double> Co2Emissions { get; set; }
    [Display(Name = "Mileage")]
    public Nullable<int> mileage { get; set; }
    [Display(Name = "Year")]
    public Nullable<int> year { get; set; }
    [Display(Name = "Doors")]
    public Nullable<int> doors { get; set; }
    [Display(Name = "Seats")]
    public Nullable<int> seats { get; set; }
    [Display(Name = "Plate")]
    public string plate { get; set; }
    [Display(Name = "Price")]
    public Nullable<int> price { get; set; }
    [Display(Name = "Short Description")]
    public string shortDescription { get; set; }
    [Display(Name = "Long Description")]
    public string longDescription { get; set; }
    [Display(Name = "Sold")]
    public bool sold { get; set; }
    [Display(Name = "Active")]
    public bool active { get; set; }
    [Display(Name = "Date Added")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy hh:mm}", ApplyFormatInEditMode = true)]
    public Nullable<System.DateTime> dateAdded { get; set; }
    [Display(Name = "Date Sold")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy hh:mm}", ApplyFormatInEditMode = true)]
    public Nullable<System.DateTime> dateSold { get; set; }

    public virtual bodytype bodytype { get; set; }
    public virtual color color { get; set; }
    public virtual fuel fuel { get; set; }
    public virtual manufacturer manufacturer { get; set; }
    public virtual model model { get; set; }
    public virtual transmission transmission { get; set; }
    public virtual version version { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<carimage> carimages { get; set; }
}

CONTROLLER控制器

Cars汽车

    // GET: cars/Create
    public ActionResult Create()
    {
        ViewBag.bodytypeId = new SelectList(db.bodytypes, "id", "name");
        ViewBag.colorId = new SelectList(db.colors, "id", "name");
        ViewBag.fuelId = new SelectList(db.fuels, "id", "name");
        ViewBag.manufacturerId = new SelectList(db.manufacturers, "id", "name");
        ViewBag.modelId = new SelectList(db.models, "id", "name");
        ViewBag.transmissionId = new SelectList(db.transmissions, "id", "name");
        ViewBag.versionId = new SelectList(db.versions, "id", "name");
        return View();
    }

    // POST: cars/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "id,bodytypeId,manufacturerId,modelId,versionId,fuelId,transmissionId,colorId,horsePower,kw,cc,Co2Emissions,mileage,year,doors,seats,plate,price,shortDescription,longDescription,sold,active,dateAdded,dateSold")] car car)
    {
        if (ModelState.IsValid)
        {
            db.cars.Add(car);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.bodytypeId = new SelectList(db.bodytypes, "id", "name", car.bodytypeId);
        ViewBag.colorId = new SelectList(db.colors, "id", "name", car.colorId);
        ViewBag.fuelId = new SelectList(db.fuels, "id", "name", car.fuelId);
        ViewBag.manufacturerId = new SelectList(db.manufacturers, "id", "name", car.manufacturerId);
        ViewBag.modelId = new SelectList(db.models, "id", "name", car.modelId);
        ViewBag.transmissionId = new SelectList(db.transmissions, "id", "name", car.transmissionId);
        ViewBag.versionId = new SelectList(db.versions, "id", "name", car.versionId);
        return View(car);
    }

VIEW看法

Create Car创建汽车

@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>car</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.bodytypeId, "bodytypeId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("bodytypeId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.bodytypeId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.manufacturerId, "manufacturerId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("manufacturerId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.manufacturerId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.modelId, "modelId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("modelId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.modelId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.versionId, "versionId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("versionId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.versionId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.fuelId, "fuelId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("fuelId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.fuelId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.transmissionId, "transmissionId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("transmissionId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.transmissionId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.colorId, "colorId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("colorId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.colorId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.horsePower, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.horsePower, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.horsePower, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.kw, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.kw, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.kw, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.cc, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.cc, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.cc, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Co2Emissions, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Co2Emissions, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Co2Emissions, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.mileage, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.mileage, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.mileage, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.year, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.year, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.year, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.doors, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.doors, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.doors, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.seats, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.seats, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.seats, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.plate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.plate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.plate, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.price, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.price, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.price, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.shortDescription, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.shortDescription, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.shortDescription, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.longDescription, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.longDescription, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.longDescription, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.sold, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.EditorFor(model => model.sold)
                @Html.ValidationMessageFor(model => model.sold, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.active, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.EditorFor(model => model.active)
                @Html.ValidationMessageFor(model => model.active, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.dateAdded, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.dateAdded, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.dateAdded, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.dateSold, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.dateSold, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.dateSold, "", new { @class = "text-danger" })
        </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>

The problem is in the controller in this line:问题出在这一行的控制器中:

 ViewBag.modelId = new SelectList(db.models, "id", "name");

This loads all available models from the db as options.这将从数据库中加载所有可用模型作为选项。 I guess you do not know the manufacturer at this point.我猜您此时不知道制造商。 (Else you can add a simple where clause here: db.models.Where(mdl => mdl.manufacturer == knownManufacturer) ). (否则,您可以在此处添加一个简单的 where 子句: db.models.Where(mdl => mdl.manufacturer == knownManufacturer) )。

A solution to filter the options on the client side would be to add the manufacturer as additional html attribute to the <option> tags for the models.在客户端过滤选项的解决方案是将制造商作为附加 html 属性添加到模型的<option>标签中。 adding html class tag under option in html dropdownlist 在 html 下拉列表中的选项下添加 html 类标签

Then use javascript that listens to changes of the manufacturer dropdown and hides all options that do not match the selected manufacturer.然后使用 javascript 侦听制造商下拉列表的更改并隐藏与所选制造商不匹配的所有选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将嵌套集合的序列化限制为仅在带有实体框架4的C#API MVC 4中显示ID - Limit serialization of nested collections to only show IDs in C# API MVC 4 with Entity Framework 4 C# 9 - 使用实体框架更新记录的仅初始化属性 - C# 9 - updating init-only properties on records with Entity Framework C# 实体框架:仅更新第一批记录并停止 - C# Entity Framework: Update Only First Batch Records and Stop C#MVC实体框架仅保存最后一行 - C# MVC Entity Framework only saving last row 如何使用实体框架在C#,ASP.NET MVC 3中的两个日期之间获取记录? - How to get records between two dates in C#, ASP.NET MVC 3 using Entity Framework? c# 获取每个组中存在的记录 ASP.NET MVC Entity Framework - c# get records which exist in each group ASP.NET MVC Entity Framework c#实体框架选择到派生子级 - c# Entity Framework select into derived child 在实体框架C#中从父实体获取子实体 - Getting child entity from parent entity in entity framework c# C#实体框架MVC Web API - C# Entity Framework MVC Web API 调用DataContext.SaveChanges()时,C#MVC实体框架,子ID,孙ID不必要地增加 - C# MVC Entity Framework, child ID, grandchild ID is unnecessarily incrementing when DataContext.SaveChanges() is called
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM