我的 ViewModel 中有 2 个属性
class ViewModel1
{
Dictonary<int, string> PossibleValues {get;set;}//key/value
int SelectedKey {get;set}
}
我想使用 Html.DropDownListFor 编辑它
我想让 MVC 自动将数据序列化到 ViewModel 中/从 ViewModel 中序列化,这样我就可以执行以下操作
public ActionResult Edit(ViewModel1 model) ...
实现此目标的最佳方法是什么?
最佳答案
正如 womp 所说,浏览器只会提交下拉列表的选定值。这很容易被默认的模型 Binder 绑定(bind),见下文。
如果您没有在客户端编辑 PossibleValues 列表,则无需将它们提交回来。如果您需要重新填充列表,请使用您最初填充字典的相同方法在您的发布操作中在服务器端进行。
例如在你的页面中:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ViewModel1>" %>
<!-- some html here -->
<%= Html.DropDownListFor(x => x.SelectedKey, new SelectList(Model.PossibleValues, "key", "value"))%>
在你的 Controller 中
[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 对象的方法。
关于c# - ASP.NET MVC ViewModel 和 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2167166/