c# - C# MVC 中带有 foreach 循环的 DropDownList

标签 c# asp.net-mvc

原版

我有一个网站,可以在其中管理汽车、品牌和汽车型号。现在我有 Controller 、模型和 View ,应用程序正在运行,所有内容都是由 Visual Studio 自动生成的,并且我正在使用 Entity Framework (首先是数据库)。

当我尝试创建汽车时,品牌和汽车型号的下拉菜单并未像我想要的那样层叠。

我有一个解决方案:向每个选择(下拉列表)上的每个选项标签添加一个类(或其他属性/属性)。然后,我会用 JS 来完成剩下的事情。我只是想知道如何执行 foreach 循环来构建我的下拉列表,即使这不是最好的解决方案,我不会讨论这一点。请记住,我需要对汽车 View 内的汽车模型执行 foreach 循环。

编辑

汽车 View

@model MyApp.Models.car

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())

{
    @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>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

汽车型号

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace MyApp.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    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

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MyApp.Models;

namespace MyApp.Controllers
{
    public class carsController : Controller
    {
        private MyAppEntities db = new MyAppEntities();

        // GET: cars
        public ActionResult Index(string id)
        {
            string searchString = id;
            var cars = db.cars.Include(c => c.bodytype).Include(c => c.color).Include(c => c.fuel).Include(c => c.manufacturer).Include(c => c.model).Include(c => c.transmission).Include(c => c.version);

            if (!String.IsNullOrEmpty(searchString))
            {
                cars = cars.Where(s => s.bodytype.name.Contains(searchString) || 
                    s.cc.ToString().Contains(searchString) ||
                    s.Co2Emissions.ToString().Contains(searchString) ||
                    s.color.name.Contains(searchString) ||
                    s.dateAdded.Value.ToString("dd-mm-yyyy").Contains(searchString) ||
                    s.dateSold.Value.ToString("dd-mm-yyyy").Contains(searchString) ||
                    s.doors.ToString().Contains(searchString) ||
                    s.fuel.name.Contains(searchString) ||
                    s.horsePower.ToString().Contains(searchString) ||
                    s.id.ToString().Contains(searchString) ||
                    s.kw.ToString().Contains(searchString) ||
                    s.longDescription.Contains(searchString) ||
                    s.manufacturer.name.Contains(searchString) ||
                    s.mileage.ToString().Contains(searchString) ||
                    s.model.name.Contains(searchString) ||
                    s.plate.Contains(searchString) ||
                    s.price.ToString().Contains(searchString) ||
                    s.seats.ToString().Contains(searchString) ||
                    s.shortDescription.Contains(searchString) ||
                    s.transmission.name.Contains(searchString) ||
                    s.version.name.Contains(searchString) ||
                    s.year.ToString().Contains(searchString)
                );
            }

            return View(cars.ToList());
        }

        // GET: cars/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            car car = db.cars.Find(id);
            if (car == null)
            {
                return HttpNotFound();
            }
            return View(car);
        }

        // 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);
        }

        // GET: cars/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            car car = db.cars.Find(id);
            if (car == null)
            {
                return HttpNotFound();
            }
            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);
        }

        // POST: cars/Edit/5
        // 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 Edit([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.Entry(car).State = EntityState.Modified;
                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);
        }

        // GET: cars/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            car car = db.cars.Find(id);
            if (car == null)
            {
                return HttpNotFound();
            }
            return View(car);
        }

        // POST: cars/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            car car = db.cars.Find(id);
            db.cars.Remove(car);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

最佳答案

原创

使用ASP.NET MVC,您可以使用服务器端预处理将服务器端模型绑定(bind)到.cshtml。在标记中,您可以使用标签助手来构建通用控件和用户输入组件,这就是 razor View 引擎发挥作用的地方。 Odeto-Code by Scott Allen有一篇很棒的文章介绍了如何结合使用这些技术来专门构建下拉列表控件。

这是示例的一部分,.cshtml:

@Html.LabelFor(m=>m.SelectedFlavorId)
@Html.DropDownListFor(m => m.SelectedFlavorId, Model.FlavorItems)
@Html.ValidationMessageFor(m=>m.SelectedFlavorId)
<input type="submit" value="Submit" />

这是相应的模型,ViewModel.cs:

public class ViewModel
{
    private readonly List<IceCreamFlavor> _flavors;

    [Display(Name = "Favorite Flavor")]
    public int SelectedFlavorId { get; set; }

    public IEnumerable<SelectListItem> FlavorItems
    {
        get { return new SelectList(_flavors, "Id", "Name");}
    }
}

作为附加资源,实际上还有其他几个 stackoverflow 问答,涵盖了与此类似的问题,here is one that is noteable .

更新1

I just want to know how can I do a foreach loop to build my dropdown

您再次可以在此处使用 razor View 引擎。它允许与服务器端 C# 模型进行交互,并提供一种从中构建 HTML 标记的方法。这是一个例子:

<select>
    @{
        foreach (var item in Model.ListOfItems)
        {
            <option value="item.Value" customAttribute="item.SomethingSpecial">
                item.Name
            </option>
        }
    }
</select>

更新2

您的汽车模型未定义模型列表。您需要指定选项才能执行 foreach。换句话说,您无法从非列表的 C# 模型上的属性构建 dropdownlist。这有帮助吗?

关于c# - C# MVC 中带有 foreach 循环的 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36198809/

相关文章:

asp.net-mvc - Autofac 3.4 缺失,而 3.5 被调用

c# - 使用 'BETWEEN' 检索字段时出错

c# - 如何将 C# datetime 舍入到 datetime2(0)

c# - 扩展基础移动 Azure 示例(.net 后端)

asp.net-mvc - MVC 在测试方法中获取查看 HTML 输出

asp.net-mvc - 使用 MVC 绑定(bind)具有数组的 QueryString

c# - OOP 说明

c# - 使用带有 $ 符号的变量反序列化 JSON

asp.net-mvc - 从 View 页面删除操作

c# - 具有分布式 session 的 ASP.Net Core Identity