gpt4 book ai didi

c# - ASP.NET MVC ViewModel 和 DropDownList

转载 作者:太空狗 更新时间:2023-10-29 22:24:57 24 4
gpt4 key购买 nike

我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com