【问题标题】:ASP.NET MVC ViewModel and DropDownListASP.NET MVC ViewModel 和 DropDownList
【发布时间】:2010-01-30 07:15:09
【问题描述】:

我的 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) ...

实现此目的的最佳方法是什么?

【问题讨论】:

  • 您使用的是 ASP.NET MVC 版本 1 还是 2?

标签: c# asp.net-mvc viewmodel


【解决方案1】:

正如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"))%>

在你的控制器中

[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

【讨论】:

    【解决方案2】:

    我认为您无法从表单上的下拉列表中构建字典。下拉列表只会返回一个值,您可以将其设置为 SelectedKey 属性,但您将无法从中重建 PossibleValues 字典。

    为了重构字典,您需要为其中的每个条目创建一个表单域。你可以做这样的事情,用你的字典上的 foreach 循环生成:

    <input type="hidden" name="PossibleValues[0].Key" value="key0">
    <input type="hidden" name="PossibleValues[0].Value" value="value0">
    <input type="hidden" name="PossibleValues[1].Key" value="key1">
    <input type="hidden" name="PossibleValues[1].Value" value="value1">
    .
    .
    .
    

    最终我会质疑是否需要从表单中重新填充字典。如果他们只能选择一个值,为什么 PossibleValues 不能只是从您的 ViewModel 之外的某个地方(例如在您的存储库中)查找?为什么将其与 ViewModel 一起存储?

    【讨论】:

      【解决方案3】:

      解决方案是在 ASP.NET MVC 框架中自定义 ModelBinding 这里有一些例子..

      stevesmithblog.com/blog/binding-in-asp-net-mvc

      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

      希望你觉得它们有用...

      谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-09
        • 1970-01-01
        • 2011-07-07
        相关资源
        最近更新 更多