2012-11-13 52 views
0

我在視圖如下:DropDownListFor歸國所選項目

<div class="editor-field"> 
    @Html.DropDownListFor(x => x.Subject, (IEnumerable<SelectListItem>) ViewBag.Clients) 
</div> 

這是我如何調用查看:

var list = new List<SelectListItem> 
       { 
        new SelectListItem {Text = "Gas Order", Value = "delivery"}, 
        new SelectListItem {Text = "Account Services", Value = "account"}, 
        new SelectListItem {Text = "Service Call", Value = "service"}, 
        new SelectListItem {Text = "Inquiry", Value = "inquiry"} 
       }; 
ViewBag.Clients = list; 

返回查看();

這是我模式

[Required] 
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
[DataType(DataType.Text)] 
[Display(Name = "Subject")] 
public string Subject { get; set; } 

我試圖返回回選定的值。

當我重新加載屏幕,由於屏幕上的錯誤,我得到這個錯誤:

The ViewData item that has the key 'Subject' is of type 'System.String' but must be of type 'IEnumerable'.

我假設它是由於這一行:

public string Subject { get; set; } 

如果是這種情況,我如何將選定的項目返回到我的模型?

+0

你還有困難嗎? – gdoron

+0

不行,你回答我的問題,謝謝! – ErocM

回答

1

When I reload the screen due to an error on the screen, I am getting this error...

確保ViewBag.Clients在刷新時具有正確的值。

這就是爲什麼你應該避免使用ViewBag並只能使用ViewModel。
將所有相關數據放在那裏。

+0

採取了點。我剛剛爲我的列表添加了另一個屬性,另一個用於我的選定值,然後完全刪除了ViewBag。 – ErocM

相關問題