2015-08-19 60 views
0

工作請閱讀所有信息下拉列表中沒有MVC

我有一個類:

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

將Site_cd和Sitename更改爲ID a nd名字分別在你的下拉列表中 –

回答

0

變化Site_cdidSitenamename

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

你有2個選擇這裏:

1)改變Site_cdSitenameidname分別在您的下拉幫助器中因爲這些是您正在使用的型號名稱:

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

2)創建一個視圖模型,並用DropDownListFor幫手:

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