ASP.NET MVC视图模型和DropDownList的 [英] ASP.NET MVC ViewModel and DropDownList

查看:164
本文介绍了ASP.NET MVC视图模型和DropDownList的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个属性在我的ViewModel

I have 2 properties in my ViewModel

class ViewModel1
{
    Dictonary<int, string> PossibleValues {get;set;}//key/value
    int SelectedKey {get;set}
}

我想用编辑这个Html.DropDownListFor

I want to edit this using a Html.DropDownListFor

我想MVC自动从视图模型中的数据序列化到/这样我就可以以下

I want to get MVC to auto serialize the data into/from the ViewModel so I can the following

public ActionResult Edit(ViewModel1 model) ...

什么是实现这一目标的最佳途径?

What's the best way to accomplish this?

推荐答案

由于womp说​​,浏览器将只提交一个下拉列表中选择的值。这是很容易的默认模式粘结剂粘结,见下文。

As womp said, a browser will only submit the selected value of a drop down list. This is easily bound by the default model binder, see below.

如果你没有编辑客户端上的PossibleValues​​列表,则没有必要提交他们回来。如果您需要重新填充列表,然后做服务器端通过使用您最初填充字典用同样的方法您的文章的行动。

If you are not editing the PossibleValues list on the client then there is no need to submit them back. If you need to repopulate the list then do it server side in your post action by using the same method you originally populated the Dictionary with.

例如在你页面:

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

Where GetDictionary() is a method that returns your populated Dictionary object.

<一个href=\"http://stackoverflow.com/questions/1398196/getting-values-from-an-asp-net-mvc-dropdownlist\">See有关详细信息,这类似的问题

这篇关于ASP.NET MVC视图模型和DropDownList的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆