2010-01-30 125 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

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

感谢