jam*_*o00 5 c# asp.net-mvc viewmodel
我的ViewModel中有2个属性
class ViewModel1
{
Dictonary<int, string> PossibleValues {get;set;}//key/value
int SelectedKey {get;set}
}
Run Code Online (Sandbox Code Playgroud)
我想使用Html.DropDownListFor编辑它
我想让MVC自动将数据序列化到ViewModel中或从ViewModel序列化,以便我可以进行以下操作
public ActionResult Edit(ViewModel1 model) ...
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最佳方法是什么?
Dav*_*enn 11
正如womp所说,浏览器只会提交下拉列表的选定值.这很容易被默认的模型绑定器绑定,见下文.
如果您没有在客户端上编辑PossibleValues列表,则无需将其提交回来.如果您需要重新填充列表,请使用与最初填充"词典"相同的方法在后期操作中执行服务器端.
例如在您的页面中:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ViewModel1>" %>
<!-- some html here -->
<%= Html.DropDownListFor(x => x.SelectedKey, new SelectList(Model.PossibleValues, "key", "value"))%>
Run Code Online (Sandbox Code Playgroud)
在你的控制器中
[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);
}
Run Code Online (Sandbox Code Playgroud)
其中GetDictionary()是一个返回填充的Dictionary对象的方法.
| 归档时间: |
|
| 查看次数: |
10936 次 |
| 最近记录: |