ASP.NET MVC ViewModel和DropDownList
我的ViewModel中有2个属性
class ViewModel1 { Dictonary PossibleValues {get;set;}//key/value int SelectedKey {get;set} }
我想使用Html.DropDownListFor编辑它
我想让MVC自动将数据序列化到ViewModel中或从ViewModel中自动序列化,以便我可以进行以下操作
public ActionResult Edit(ViewModel1 model) ...
实现这一目标的最佳方法是什么?
正如womp所说,浏览器只会提交下拉列表的选定值。 这很容易被默认的模型绑定器绑定,见下文。
如果您没有在客户端上编辑PossibleValues列表,则无需将其提交回来。 如果您需要重新填充列表,请使用与最初填充“词典”相同的方法在后期操作中执行服务器端。
例如在你的页面中:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %> <%= 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对象的方法。
有关详细信息,请参阅此类似问题
我认为您无法从表单上的下拉列表构建字典。 下拉列表只会返回一个值,您可以将其设置为SelectedKey
属性,但您将无法从中重新构建PossibleValues
字典。
为了重建字典,您需要为其中的每个条目都有一个表单字段。 你可以做这样的事情,用你的字典上的foreach循环生成:
. . .
最后我会质疑是否需要从表单中重新填充字典。 如果他们只能选择一个值,为什么PossibleValues不会只是从ViewModel之外的某个地方查找(就像在您的存储库中一样?)为什么要用ViewModel存储它?
解决方案是ASP.NET MVC框架中的自定义ModelBinding,这里有一些例子..
stevesmithblog.com/blog/binding-in-asp-net-mvc
http://www.singingeels.com/Articles/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
希望你发现它们有用……
谢谢