c# - ASP.NET MVC ViewModel 和 DropDownList

标签 c# asp.net-mvc viewmodel

我的 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 对象的方法。

See this similar question for more details

关于c# - ASP.NET MVC ViewModel 和 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2167166/

相关文章:

c# - 如何在代码中使用 Binding?

c# - 为什么需要处理图形?

c# - 如何在没有显式引用的情况下访问打开的 DbContext?

c# - MVVM 中的 ViewModel 是什么

xaml - 设置 datacontext 时如何摆脱设计时 XAML 错误 "Object reference not set to an instance of object"

java - SavedState ViewModel 使用 SavedStateViewModelFactory

c# - 使用 async 和 await 的最佳性能

c# - 为什么添加这一行会弄乱我的 NHibernate 映射?

asp.net-mvc - asp.net核心开发模型

asp.net-mvc - 使用 ASP.NET MVC MapRoute 重定向