请阅读所有信息
我有一个班级:
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();'
}
答案 0 :(得分:1)
这里有2个选项:
1)在您的下拉帮手中分别将Site_cd
和Sitename
更改为id
和name
,因为这些是您在模型中使用的名称:
@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();'
}
答案 1 :(得分:0)
将Site_cd
更改为id
,将Sitename
更改为name
:
@Html.DropDownList("CaseType", new SelectList(Model.ToList(), "id","name"))