下拉列表在MVC中不起作用

本文关键字:不起作用 MVC 下拉列表 | 更新日期: 2023-09-27 18:08:51

请阅读所有信息

我有一个类:

public class Cars
{
   public int id{get; set;}
   public string name{get; set;}
}

此外,我在我的控制器方法中使用存储过程从数据库传递数据,如下所示:

public ActionResult Index()
{
   db = new CarEntities();
   var listOfCars = (from o in db.Get_Car_List()
                 select new Get_Car_List_Result
                 {
                     id = o.id,
                     name = o.name
                 }).ToList<Get_Car_List_Result>();
   return View(listOfCars);
}
在Index.cshtml:

@model IEnumerable<Cars.Models.Get_Car_List_Result>
@{
     ViewBag.Title = "Home Page";
 }
<div style="align-content:center;">
   @using (Html.BeginForm())
   {
      <p>My Caseload:
         @Html.DropDownList("CaseType", new SelectList(Model.ToList(), "Site_cd","Sitename"))
         <input type="submit" value="Find" />
      </p>
   }
</div>

我需要从下拉列表中检索数据到:

[HttpPost]
public ActionResult Index(string CaseType)
{
   db = new CarEntities();
   var car_id= from o in db.Get_CarSites()
        where o.name== CaseType
        select o.id;                        
   //then run another query
   return View();'
}

下拉列表在MVC中不起作用

你有两个选择:

1)在您的下拉帮助器中分别将Site_cdSitename更改为idname,因为这些是您在模型中使用的名称:

@Html.DropDownList("CaseType", new SelectList(Model.ToList(), "id","name"))
2)创建视图模型并使用DropDownListFor helper:
public class CarsViewModel
{
     public int SelectedCarId {get;set;}
     public IList<SelectListItem> Cars {get;set;}
} 

视图:

@model CarsViewModel
@{
     ViewBag.Title = "Home Page";
 }
<div style="align-content:center;">
@using (Html.BeginForm())
{
<p>My Caseload:
  @Html.DropDownListFor(m=>m.SelectedCarId, Model.Cars )
  <input type="submit" value="Find" />
</p>
}
</div>

控制器:

public ActionResult Index()
{
    db = new CarEntities();
    var model = new CarsViewModel
    {
        Cars = db.Get_Car_List().Select(c=> new SelectListItem
                {
                   Value = c.id.ToString(),
                   Text = c.name
                }).ToList()
    };
    return View(model);
 }

[HttpPost]
public ActionResult Index(CarsViewModel model)
{
    db = new CarEntities();
    var car_id= from o in db.Get_CarSites()
        where o.name == model.SelectedCarId
        select o.id;                        
    //then run another query
    'return View();'
}

Site_cd改为id, Sitename改为name:

@Html.DropDownList("CaseType", new SelectList(Model.ToList(), "id","name"))