2010-01-30 133 views
5

我有2個屬性在我的ViewModelASP.NET MVC視圖模型和DropDownList的

class ViewModel1 
{ 
    Dictonary<int, string> PossibleValues {get;set;}//key/value 
    int SelectedKey {get;set} 
} 

我想用一個Html.DropDownListFor

我想MVC自動將數據序列化爲編輯這個/從ViewModel,所以我可以以下

public ActionResult Edit(ViewModel1 model) ... 

什麼是最好的方法來實現這一目標?

+0

您使用的是ASP.NET MVC版本1還是2? – 2010-01-30 11:23:01

+0

我正在使用版本2 – jameszhao00 2010-01-30 20:15:33

回答

11

正如womp說,瀏覽器將只能提交一個下拉列表中選擇的值。這很容易被默認的模型綁定器綁定,見下文。

如果您未在客戶端上編輯PossibleValues列表,則無需將其提交回去。如果您需要重新填充列表,請在您的發佈操作中使用您最初填寫Dictionary的相同方法在服務器端執行此操作。

例如,在你頁面:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ViewModel1>" %> 
<!-- some html here --> 
<%= Html.DropDownListFor(x => x.SelectedKey, new SelectList(Model.PossibleValues, "key", "value"))%> 

在你的控制器

[AcceptVerbs(HttpVerbs.Get)] 
public ViewResult Edit() { 
var model = new ViewModel1 { 
    PossibleValues = GetDictionary() //populate your Dictionary here 
}; 
return View(model); 
} 

[AcceptVerbs(HttpVerbs.Post)] 
public ViewResult Edit(ViewModel1 model) { //default model binding 
    model.PossibleValues = GetDictionary(); //repopulate your Dictionary here 
    return View(model); 
} 

凡GetDictionary()是返回你的填充Dictionary對象的方法。

See this similar question for more details

0

我不認爲你可以從窗體上的下拉列表中構建字典。下拉列表只會發回一個值,您可以將其設置爲您的SelectedKey屬性,但您將無法從中重新構建PossibleValues字典。

爲了重建一本字典,你需要爲每一個條目都有一個表單域。你可以做這樣的事情,有一個foreach循環在你的字典生成:

<input type="hidden" name="PossibleValues[0].Key" value="key0"> 
<input type="hidden" name="PossibleValues[0].Value" value="value0"> 
<input type="hidden" name="PossibleValues[1].Key" value="key1"> 
<input type="hidden" name="PossibleValues[1].Value" value="value1"> 
. 
. 
. 

最終,我會質疑是否有必要重新填充從字典的形式。如果他們只能選擇一個值,那麼PossibleValues爲什麼不能從ViewModel之外的某個地方進行查找(就像在你的存儲庫中一樣?)爲什麼將它與ViewModel一起存儲?

0

該解決方案在ASP.NET MVC框架這裏定製ModelBinding是一些例子..

stevesmithblog.com/blog/binding-in-asp-net-mvc

www.singingeels.com/文章/ Model_Binders_in_ASPNET_MVC.aspx

odetocode.com/Blogs/scott/archive/2009/04/27/12788.aspx

odetocode.com/Blogs/scott/archive/2009/05/05/12801。 aspx

希望你能找到他們有用...

感謝