MVC2架构中ViewData如何实现模型与视图的解耦?

2026-03-30 13:081阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计281个文字,预计阅读时间需要2分钟。

MVC2架构中ViewData如何实现模型与视图的解耦?

我正在尝试通过ViewData将一些项目列表传递给视图以创建下拉列表。这应该不会太难,但我作为MVC的新手,可能会遗漏一些明显的细节。控制器将列表分配给ViewData:ViewData[ImageLocatons]

我正在尝试通过ViewData将一些项目列表传递给视图以创建下拉列表.这应该不会太难,但我是MVC的新手,所以我可能会遗漏一些明显的东西.

控制器将列表分配给ViewData:

ViewData["ImageLocatons"] = new SelectList(gvr.ImageLocations);

并且视图尝试将其呈现到下拉列表中:

<%= Html.DropDownList("Location", ViewData["ImageLocations"] as SelectList) %>

但是,当我运行它时,我收到此错误:
没有类型为“IEnumerable”的ViewData项具有“位置”键.

任何想法为什么这不起作用?此外,它不应该寻找关键的“ImageLocations”而不是位置?

如果您使用:

ViewData["Location"] = new SelectList(gvr.ImageLocations);

MVC2架构中ViewData如何实现模型与视图的解耦?

<%= Html.DropDownList("Location") %>

你的生活会轻松多了.

在示例中设置ViewData时,还要查看拼写错误(缺少i)(ImageLocatons => ImageLocations).这会导致传递给DropDownList的第二个参数为null.这将导致MVC引擎搜索Location.

本文共计281个文字,预计阅读时间需要2分钟。

MVC2架构中ViewData如何实现模型与视图的解耦?

我正在尝试通过ViewData将一些项目列表传递给视图以创建下拉列表。这应该不会太难,但我作为MVC的新手,可能会遗漏一些明显的细节。控制器将列表分配给ViewData:ViewData[ImageLocatons]

我正在尝试通过ViewData将一些项目列表传递给视图以创建下拉列表.这应该不会太难,但我是MVC的新手,所以我可能会遗漏一些明显的东西.

控制器将列表分配给ViewData:

ViewData["ImageLocatons"] = new SelectList(gvr.ImageLocations);

并且视图尝试将其呈现到下拉列表中:

<%= Html.DropDownList("Location", ViewData["ImageLocations"] as SelectList) %>

但是,当我运行它时,我收到此错误:
没有类型为“IEnumerable”的ViewData项具有“位置”键.

任何想法为什么这不起作用?此外,它不应该寻找关键的“ImageLocations”而不是位置?

如果您使用:

ViewData["Location"] = new SelectList(gvr.ImageLocations);

MVC2架构中ViewData如何实现模型与视图的解耦?

<%= Html.DropDownList("Location") %>

你的生活会轻松多了.

在示例中设置ViewData时,还要查看拼写错误(缺少i)(ImageLocatons => ImageLocations).这会导致传递给DropDownList的第二个参数为null.这将导致MVC引擎搜索Location.