2014-01-29 31 views
0

我一直試圖填充一個下拉列表一段時間,並希望得到一些幫助。我有我的模型和viewmodel,我試圖填充下拉列表並將其發送到視圖,以便用戶可以選擇cartype並單擊submit。ASP.NET MVC填充下拉列表

public class Cars 
{ 
    public int CarId { get; set; } 
    public string Name { get; set; } 
} 

public class CarViewModel 
{ 
    public int SelectedCarId { get; set; } 
    public IEnumerable<SelectListItem> CarTypes; 

} 

public ActionResult FillDropDown() 
{ 
    var model = new ViewModel(); 
    model.CarTypes = (from s in context.CarTypes 
         select new SelectListItem() 
         { 
         Text = s.Name, 
         Value = SqlFunctions.StringConvert((double)s.Id).Trim(), 
         }).ToList<SelectListItem>(); 

    return View(model); 
} 

所以我想幫助一下如何在視圖中渲染它。我嘗試了以下,但我得到一個nullreference異常。

@Html.BeginForm("FillDropDownList","Home", FormMethod.Post,null) 
{ 
    @Html.DropDownListFor(x => x.SelectedCarId, Model.CarTypes); 
    <input type="submit" value="submit" /> 
} 
+1

在動作結果中使用'CarViewModel'而不是'ViewModel'。 – ssilas777

+1

你從哪裏得到例外? 'context'從哪裏來?它是'空'嗎?是'Model.CarTypes'還是'Model'' null'? – meilke

+0

當我將它發送到視圖時,我可以看到它填充了正確的數據:return View(model)。但是在行:@ Html.DropDownListFor(x => x.SelectedCarId,Model.CarTypes);我得到一個null引用異常,說Model.CarTypes是空的。 – Zedex

回答

0

嘗試使用CarViewModel而不是ViewModel。

public ActionResult FillDropDown() 
{ 
    var model = new CarViewModel(); //CarViewModel instead of ViewModel 
    model.CarTypes = (from s in context.CarTypes 
        select new SelectListItem() 
        { 
         Text = s.Name, 
         Value = SqlFunctions.StringConvert((double)s.Id).Trim(), 
        }).ToList<SelectListItem>(); 

    return View(model); 
} 

編輯:

更改CarViewModel您的IEnumerable屬性爲的SelectList

public class CarViewModel 
{ 
    public int SelectedCarId { get; set; } 
    public SelectList CarTypes; 
} 

確保SelectListItem不爲空,在FillDropDown()方法。

+0

thx!實際上這行不起作用:@ Html.DropDownListFor(x => x.SelectedCarId,Model.CarTypes);我想回發selectedCarId。該模型填充了正確的數據。 – Zedex

+0

我再次更新了我的答案。 – SamekaTV