ASP.NET MVC 将多个数据实例从控制器传递到视图
我正在尝试构建 ASP.NET MVC 2 应用程序。我想将数据从控制器传递到视图。当它只是一个单一的数据结构时我能够通过它。在控制器中:
private ArticlesDBEntities _db = new ArticlesDBEntities();
public ActionResult Articles()
{
return View(_db.ArticleSet.ToList());
}
在视图中,我像这样迭代列表:(
<div id="demo1">
<% foreach (var item in Model) { %>
<ul>
<li id="<%= Html.Encode(item.Id) %>">
<a href="#"><%= Html.Encode(item.Title) %></a>
<ul>
<li id="phtml_2">
<a href="#">Child node 1</a>
</li>
<li id="phtml_3">
<a href="#">Child node 2</a>
</li>
</ul>
</li>
</ul>
<% } %>
</div>
子节点现在出于测试原因,没有真正的角色)
但是,我现在想要处理用户尝试时的场景访问 Home/Articles/Id,不仅传递文章列表(用于填充 jsTree),还传递文章本身,这样我也可以显示它。但是,当我尝试像这样创建 ViewData 对象时:
public ActionResult Articles()
{
ViewData["articlesList"] = _db.ArticleSet.ToList();
return View();
}
我无法找到如何在视图中迭代它。
I'm trying to build an ASP.NET MVC 2 application. I want to pass data to a view from a controller. I am able to pass it when it is only a single data structure. In the controller:
private ArticlesDBEntities _db = new ArticlesDBEntities();
public ActionResult Articles()
{
return View(_db.ArticleSet.ToList());
}
and in the view, I iterated over the list like so:
<div id="demo1">
<% foreach (var item in Model) { %>
<ul>
<li id="<%= Html.Encode(item.Id) %>">
<a href="#"><%= Html.Encode(item.Title) %></a>
<ul>
<li id="phtml_2">
<a href="#">Child node 1</a>
</li>
<li id="phtml_3">
<a href="#">Child node 2</a>
</li>
</ul>
</li>
</ul>
<% } %>
</div>
(the child nodes are for testing reasons right now, don't have a real role)
However, I now want to handle a scenario when a user tries to access Home/Articles/Id, and not only pass the article list (used for populating a jsTree), but also the Article itself, so I can show it as well. However, when I tried creating a ViewData object like so:
public ActionResult Articles()
{
ViewData["articlesList"] = _db.ArticleSet.ToList();
return View();
}
I was unable to find out how to iterate over it in the view.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就传递多个数据项而言,您可以使用视图模型(首选方式)或通过视图数据来完成。如果你想通过视图模型传递它,你可以做类似的事情
你可以填充这个视图模型并将其传递给
视图中的视图你可以访问它就像
迭代ViewData[“key”]你必须将其转换为相应的对象,例如
as far as passing multiple data items is concerned u can do it using view models (preferred way) or by viewdata. if u want to pass it through View model u can do something like
u can populate this view model and pass it to view
in view u can access it like
to iterate over ViewData["key"] u have to cast it to corresponding object like
在您的视图中,您应该能够执行
另一种方法:创建一个新的视图模型类,该类将同时保存文章和列表:
并将其传递到您的视图中。然后您可以通过 Model 属性访问它,并且您将获得强类型。
In your View you should be able to do
An alternative approach would be to create a new view model class that would hold both the article and the list:
and pass that into your view. Then you can access it through the
Model
property and you will get strong typing.