【问题标题】:DropDownList with foreach loop in C# MVC在 C# MVC 中使用 foreach 循环的 DropDownList
【发布时间】:2016-07-11 23:05:34
【问题描述】:

原创

我有一个可以管理汽车、品牌和车型的网站。现在我有控制器、模型和视图,应用程序正在运行,一切都是由 Visual Studio 自动生成的,我正在使用实体框架(首先是数据库)。

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

我有一个解决方案:在每个选择(下拉菜单)的每个选项标签中添加一个类(或其他属性/属性)。然后,用 JS,我会做剩下的。我只想知道如何做一个 foreach 循环来构建我的下拉列表,即使它不是最好的解决方案,我也不会讨论这个。请记住,我需要在 Cars 视图中对 carmodel 模型执行一个 foreach 循环。

编辑

汽车视图

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

    }
}

汽车控制器

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

【问题讨论】:

  • 你写了很多,但实际上你没有说什么“......不像我想要的那样层叠”。你想要什么?它们长什么样子?
  • 对不起。例如,当我选择标致品牌时,我希望其他下拉列表(汽车型号)仅显示标致车型,而不是所有品牌的所有车型。但这不是问题,我可以用 JS 做到这一点,就像我说的那样,我只想知道如何在视图中为每个循环构建一个下拉列表。请记住,下拉菜单位于 Cars View 中,并且必须包含 CarModel 数据。
  • 我会在服务器端做。当您选择一个品牌时,一个快速的 AJAX 请求将获取项目以填充模型下拉列表。我认为这比客户端过滤要容易得多(您需要提前检索每个品牌的所有可能模型)。
  • @DA_Interlog 让模型下拉列表独立于品牌下拉列表的想法可以通过简洁的数据库设计来实现
  • 2 个表,brand 表仅包含品牌和模型表,模型和品牌都作为 FK。选择品牌后,获取 ID 发送 AJAX 请求,然后执行 SQL 检索特定于品牌 ID 的模型并在下拉列表中重新填充数据:)

标签: c# asp.net-mvc


【解决方案1】:

原创

使用 ASP.NET MVC,您可以使用服务器端预处理将服务器端模型绑定到 .cshtml。在标记中,您可以使用标签助手来构建通用控件和用户输入组件,这就是 razor 视图引擎发挥作用的地方。 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 Q/A 涵盖了与此类似的问题,here is one that is noteable

更新 1

我只想知道如何做一个 foreach 循环来构建我的下拉列表

再次,您可以在此处使用剃刀视图引擎。它允许与服务器端 C# 模型进行交互,并且可以从中构建 HTML 标记。这是一个例子:

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

更新 2

car 模型没有定义模型列表。您需要指定选项是什么才能执行foreach。换句话说,您不能从不是列表的C# 模型上的属性构建dropdownlist。这有帮助吗?

【讨论】:

  • 我理解的那部分。我知道我可以做到,但我想使用模型中的数据,而不是静态文本,并且我想在下拉列表中的选项中添加第三个属性,而不是文本和值。
  • 可以在我的回答@DA_Interlog 的下拉列表中添加一个选项
  • @KTOV,我已经提请注意该方法。但是它不起作用,因为他需要向option 元素添加自定义属性。我在回答中涵盖了这两种情况。
  • @DavidPine 我应该把 ViewModel.cs 文件放在哪里?对不起,就像我说我是 MVC 的新手
  • 在您的模型目录中,它是MVC 中的“M”。你应该有这种类型的关系upload.wikimedia.org/wikipedia/commons/thumb/a/a0/…
【解决方案2】:

您可以在 C# 而不是 JS 中执行此操作,这里是一个简单的示例:

public class FindUser 
{

  // Where the items from the DB will be kept
  public Dictionary<int, string> CountryList { get; set; }

  // Used to store the users selected option
  public int SelectedCountry { get; set; }

  // A constructor to be called when the page renders
  public FindUser()
  {
      PopulateCountryDropdown();
  }

  public void PopulateLeaDropdown()
    {
        // 1. Grab your items from the database, store it within a databale
        // 2. Loop through the datatable and add each row to the list

        CountryList = new Dictionary<int, string>();

        foreach(DataRow row in dt.Rows)
        {
            CountryList.Add(Convert.ToInt32(row["ID"]), row["country"].ToString());
        }
    }
}

然后在你的前端添加:

@Html.DropDownListFor(u => u.SelectedCountry, new SelectList(Model.CountryList, "Key", "Value"), "Select your country", new { @class = "form-control countries", id = "country_list" })

【讨论】:

  • 如何在下拉菜单中为每个选项添加一个类属性?
【解决方案3】:

找到解决方案HERE

具有以下 2 个表的学校数据库。

StateMaster
DistrictMaster

第 1 步

打开 Visual Studio,然后选择 File >> New >> Project,然后选择 ASP.Net MVC 4 Web Application。

第 2 步

选择 Internet 应用程序,然后单击确定。

第 3 步

选择 Model 文件夹,然后创建一个新的 Model 类。

StudentModel.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  

namespace MvcDemoApplication.Models  
{  
    public class StudentModel  
    {  
        public IList<SelectListItem> StateNames { get; set; }  
        public IList<SelectListItem> DistrictNames { get; set; }  
    }  
}

第 4 步

创建一个 .edmx 文件并连接数据库。

第 5 步

创建一个新的控制器。在本文中,我创建了 DropDownListController.cs。

DropDownListController.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
using MvcDemoApplication.Models;  

namespace MvcDemoApplication.Controllers  
{  
    public class DropDownListController : Controller  
    {  
        //  
        // GET: /DropDownList/  
        SchoolEntities schoolEntity = new SchoolEntities();  
        public ActionResult Index()  
        {  
            List<SelectListItem> stateNames = new List<SelectListItem>();  
            StudentModel stuModel=new StudentModel();  

            List<StateMaster> states = schoolEntity.StateMasters.ToList();  
            states.ForEach(x =>  
                {  
          stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });  
                });  
            stuModel.StateNames = stateNames;  
            return View(stuModel);  
        }  
    }  
}

Index.cshtml

@model MvcDemoApplication.Models.StudentModel  
@{  
    ViewBag.Title = "Index";  
}  

<script src="~/Scripts/jquery-1.7.1.min.js"></script>  

<h2>Cascading Dropdownlist</h2>  
<table>  
    <tr>  
        <td>  
            <label>State</label>  
        </td>  
        <td>  
@Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new { @id="ddlState"});  
        </td>  
    </tr>  
</table>

了解守则

在 Studentmodel 中,我们有以下 2 个属性:

    public IList<SelectListItem> StateNames { get; set; }  
    public IList<SelectListItem> DistrictNames { get; set; }  

这里我们使用的是SelectListItem类,这个类有以下3个属性:

Selected: This is a bool type to show in a dropdown (as selected) true or false by default.

Text: This is a string type, for the dropdown text.

Value: This is string type for the value of the dropdown

如果您在下拉列表中注意到,我们也需要相同的属性。出于这个原因,我们在 Ilist 中使用 SelectListItem。

DropdownlistController.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
using MvcDemoApplication.Models;  

namespace MvcDemoApplication.Controllers  
{  
    public class DropDownListController : Controller  
    {  
        //  
        // GET: /DropDownList/  
        SchoolEntities schoolEntity = new SchoolEntities();  
        public ActionResult Index()  
        {  
            List<SelectListItem> stateNames = new List<SelectListItem>();  
            StudentModel stuModel=new StudentModel();  

            List<StateMaster> states = schoolEntity.StateMasters.ToList();  
            states.ForEach(x =>  
                {  
                    stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });  
                });  
            stuModel.StateNames = stateNames;  
            return View(stuModel);  
        }  
    }

在前面的代码中我们创建了 SchoolEntities 对象,在这个对象中所有相关的表都存在。

SchoolEntities schoolEntity = new SchoolEntities();  

List<StateMaster> states = schoolEntity.StateMasters.ToList();  

在上一行代码中,StateMasters表的所有相关数据都进入了StateMaster列表对象。

states.ForEach(x =>  
{  
   stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });  
});  

现在是时候将实体数据添加到 Text 和 value 属性中了,所有集合都将存储到 stateNames 对象中。

Index.cshtml

@model MvcDemoApplication.Models.StudentModel  
@{  
    ViewBag.Title = "Index";  
}  

<script src="~/Scripts/jquery-1.7.1.min.js"></script>  

<h2>Cascading Dropdownlist</h2>  
<table>  
    <tr>  
        <td>  
            <label>State</label>  
        </td>  
        <td>  
  @Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new { @id="ddlState"});  
        </td>  
    </tr>  
</table>

上述代码在 View 中展示了模型数据。现在来了解它是如何工作的。

@Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new { @id="ddlState"});

看前面的代码,我们这里使用了@Html帮助类来创建一个DropDownList。在 DropDownListFor 辅助类中,我们使用了 4 个参数。

x=>x.StateNames: For getting the values of the collection from the entity.

Model.StateNames: Collections of states.

“—Select--”: Default value, when the dropdown list will be populated.

new {@id=”ddlState”}: In this part we can define an id, class and name for the control.

如何在两个下拉列表之间进行级联。

DropdownlistController.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
using MvcDemoApplication.Models;  

namespace MvcDemoApplication.Controllers  
{  
    public class DropDownListController : Controller  
    {  
        //  
        // GET: /DropDownList/  
        SchoolEntities1 schoolEntity = new SchoolEntities1();  
        public ActionResult Index()  
        {  
            List<SelectListItem> stateNames = new List<SelectListItem>();  
            StudentModel stuModel=new StudentModel();  

            List<StateMaster> states = schoolEntity.StateMasters.ToList();  
            states.ForEach(x =>  
                {  
stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });  
                });  
            stuModel.StateNames = stateNames;  
            return View(stuModel);  
        }  

        [HttpPost]  
        public ActionResult GetDistrict(string stateId)  
        {  
            int statId;  
            List<SelectListItem> districtNames = new List<SelectListItem>();  
            if (!string.IsNullOrEmpty(stateId))  
            {  
                statId = Convert.ToInt32(stateId);  
List<DistrictMaster> districts = schoolEntity.DistrictMasters.Where(x => x.StateId == statId).ToList();  
                districts.ForEach(x =>  
                {  
districtNames.Add(new SelectListItem { Text = x.DistrictName, Value = x.DistrictId.ToString() });  
                });  
            }  
            return Json(districtNames, JsonRequestBehavior.AllowGet);  
        }  

    }  
}

Index.cshtml

@model MvcDemoApplication.Models.StudentModel  
@{  
    ViewBag.Title = "Index";  
}  

<script src="~/Scripts/jquery-1.7.1.min.js"></script>  

<h2>Cascading Dropdownlist</h2>  
<table>  
    <tr>  
        <td>  
            <label>State</label>  
        </td>  
        <td>  
@Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--", new { @id="ddlState"});  
        </td>  
    </tr>  
    <tr>  
        <td>  
            <label>District</label>  
        </td>  
        <td id="District">  
@Html.DropDownListFor(x => x.DistrictNames, new List<SelectListItem>(), "--Select--", new { @id="ddlDistrict"});  
        </td>  
    </tr>  
</table>  

<script type="text/javascript">  
    $(document).ready(function () {  
        $('#ddlState').change(function () {  
            $.ajax({  
                type: "post",  
                url: "/DropDownList/GetDistrict",  
                data: { stateId: $('#ddlState').val() },  
                datatype: "json",  
                traditional: true,  
                success: function (data) {  
                    var district = "<select id='ddlDistrict'>";  
                    district = district + '<option value="">--Select--</option>';  
                    for (var i = 0; i < data.length; i++)  
                    {  
                        district = district + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';  
                    }  
                    district = district + '</select>';  
                    $('#District').html(district);  
                }  
            });  
        });  
    });  
</script>

就是这样。按 F5 并运行您的代码。

【讨论】:

    【解决方案4】:

    看Nuget包Mvc.CascadeDropDown:
    https://www.nuget.org/packages/Mvc.CascadeDropDown/

    这是我的使用方法:

    @Html.CascadingDropDownListFor(m => m.ArticleGroup_Nr, "Department_Nr",
        Url.Action("GetArticleGroups"), "DepartmentNr", "-- Select item --", true,
        new { @class = "form-control", style = "width: 450px" })
    

    此处Department_Nr 指定视图中其他位置的父下拉列表 - 常规下拉列表或另一个级联下拉列表。

    然后,我在接受 DepartmentNr 参数的同一控制器上创建了一个 JSON 操作 GetArticleGroups,该参数传递父下拉列表的当前值。

    每次更改父下拉列表的值时都会调用 JSON 操作,因为 @Html.Cascading... 还会将 onchange-eventhandler 附加到父对象。

    public virtual JsonResult GetArticleGroups(int DepartmentNr)
    {
        var items = provider.ArticleGroups.Where(m => m.Parent_Nr == DepartmentNr);
        return GetJson(items); // convert items to JSON [ { "Value":"xx", "Text":"yy" } ]
    }
    
    private JsonResult GetJson(IQueryable<ICatalogueItem> items)
    {
        var data = items
            .Select(x => new { Value = x.Number, Text = x.Text })
            .OrderBy(o => o.Text);
        return Json(data, JsonRequestBehavior.AllowGet);
    }
    



    ... 或者查看这篇关于如何自己构建它的文章:
    http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/

    【讨论】:

    • 无论谁对您投了反对票,都可能担心“在另一座城堡中的答案”问题,您只需发布指向外部资源的链接即可。 meta.stackexchange.com/questions/225370/…
    • @Loofer 尝试了 nuget,但是当将“@using Mvc.CascadeDropDown”放在我的 .cshtml 视图顶部时,它不接受,说“mvc”。不存在。尝试了 web.config 的方式,也不起作用。我检查并安装了软件包,并且对“Mvc.CascadeDropDown”的引用在项目中。
    • 问彼得 B... 我只是在抱怨他的堆栈溢出礼仪。
    猜你喜欢
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2020-02-06
    • 2018-08-22
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    相关资源
    最近更新 更多