2016-03-24 3 views
0

ORIGINALDropDownList с петлей Еогеасп в C# MVC

У меня есть сайт, где я могу управлять автомобилями, марки и модели автомобиля. Сейчас у меня есть контроллеры, модели и представления, приложение работает, все было создано с помощью Visual Studio, и я использую структуру сущности (сначала базу данных).

Когда я пытаюсь создать автомобиль, выпадающие списки с марками и моделями автомобилей не каскадируют, как я хочу.

У меня есть решение: добавьте класс (или другое свойство/атрибут) к каждому тегу параметра для каждого выбора (выпадающего списка). Тогда, с JS, я сделаю все остальное. Я просто хочу знать, как я могу сделать цикл foreach для создания моего раскрывающегося списка, даже если это не лучшее решение, я не обсуждаю это. Помните, что мне нужно сделать петлю foreach к модели модели carmodel, в окне «Автомобили».

EDIT

автомобилей Просмотр

@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); 
     } 
    } 
} 
+0

Вы написали много, но на самом деле вы не сказали, что _ "... не каскадируют, как я хочу" _. Что ты хочешь? Как они выглядят? –

+0

Извините. Например, когда я выбираю марку Peugeot, я хочу, чтобы в другом выпадающем списке (модели автомобилей) отображались только модели peugeot, а не все модели для всех марок. Но это не вопрос, я могу сделать это с JS, как я уже сказал, я просто хочу знать, как создать выпадающий список с каждым циклом внутри представления. Помните, что раскрывающийся список находится внутри «Просмотр автомобилей» и должен иметь данные CarModel. –

+0

Я бы сделал это на стороне сервера. Когда вы выбираете бренд, тогда быстрый запрос AJAX получит элементы для заполнения раскрывающегося списка «Модель». Я думаю, что это намного проще, чем фильтрация на стороне клиента (где вам нужно заранее получить все возможные модели для каждой марки). –

ответ

0

Решение найдено HERE

Школа базы данных с следующие 2 таблицы.

StateMaster 
DistrictMaster 

Шаг 1

Open Visual Studio, затем выберите File >> New >> Project выберите ASP.Net MVC 4 веб-приложения.

Шаг 2

Выберите Internet Application и нажмите OK.

Шаг 3

Выберите папку модели затем создать новый класс модели.

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 

Если вы заметили в DropDownList, мы также должны одни и те же свойства. По этой причине мы используем SelectListItem в Ilist.

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

Теперь настало время, чтобы добавить данные сущности в текст и значение свойства, то все коллекции будут сохранены в объект 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 helper мы использовали 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. 

Как сделать каскадные между двумя DropDownLists.

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 и запустите свой код.

-1

Посмотрите на 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 определяет родительский выпадающее меню в другом месте в представлении - либо регулярный выпадающий список или другой каскадный выпадающий список.

Затем я создал JSON Action GetArticleGroups на том же контроллере, который принимает параметр DepartmentNr, которому передается текущее значение раскрывающегося списка родителя.

Действие JSON будет вызываться каждый раз, когда изменяется значение родительского раскрывающегося списка, потому что @Html.Cascading... также присоединяет обработчик onchange к родительскому объекту.

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/

+0

кто бы ни опустил вас, вероятно, беспокоит проблема «ответ в другом замке», в которой вы просто публикуете ссылки на внешние ресурсы. http://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer – Loofer

+0

@Loofer Пробовал nuget, но при установке ' @using Mvc.CascadeDropDown 'в верхней части моего .cshtml представления, который он не принимает, говорит' mvc. ' не существует. Пробовал путь web.config, тоже не работает. Я проверил и установил патч, и ссылка на «Mvc.CascadeDropDown» находится в проекте. –

+0

спросите Петра B ... Я просто стонал о его переполнении этикета. – Loofer

1

Оригинал

С ASP.NET MVC, вы используете сервер - предварительная обработка для привязки моделей на стороне сервера к .cshtml. Изнутри разметки вы можете использовать тег-помощники для создания общих элементов управления и пользовательских компонентов ввода, вот где запускается механизм просмотра бритвы.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.

Update 1

Я просто хочу знать, как я могу сделать петлю Еогеасп построить мой выпадающий список

Опять вы можете использовать вид двигателя бритвы здесь. Он позволяет взаимодействовать с серверной моделью C# и средством для создания надстройки HTML. Вот пример:

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

Update 2

Вы car модель не определяет список моделей. Вы должны указать, какие параметры есть для того, чтобы сделать foreach. Другими словами, вы не можете построить dropdownlist из свойства на модели C#, которая не является списком. Это помогает?

+0

эта часть я понял. Я знаю, что могу это сделать, но я хочу использовать данные из модели, а не статический текст, и я хочу добавить третий атрибут в параметры внутри раскрывающегося списка, а не текст и значение шляпы. –

+0

В раскрывающемся списке можно добавить опцию @DA_Interlog – KTOV

+0

@KTOV. Я уже обращал внимание на этот метод. Однако он не работает, так как ему нужно добавить пользовательский атрибут к элементу 'option'. Я рассмотрел оба случая в своем ответе. –

0

Вы можете сделать это в 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" }) 
+0

Как я могу добавить атрибут класса для каждой опции в раскрывающемся меню? –

Смежные вопросы