我的 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 所说,浏览器只会提交下拉列表中选定的值。这很容易被默认模型绑定器绑定,见下文。
如果您不在客户端上编辑可能值列表,则无需将它们提交回来。如果您需要重新填充列表,请使用最初填充字典的相同方法在您的发布操作中在服务器端执行此操作。
例如在您的页面中:
<%@ 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 对象的方法。
有关更多详细信息,请参阅此类似问题
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)