ASP.NET MVC 的新手(现在将 MVC3 与 Razor 结合使用),我对将对象从 Controller 传递到 View 感到困惑。具体来说,我正在试验 MVC3 和 Rob Conery 有趣的 Massive (http://blog.wekeroad.com/helpy-stuff/and-i-shall-call-it-massive)。我正在将博客作为一个简单的 Web 应用程序来进行试验。
HomeController.cs:
public ActionResult Index()
{
var table = new DynamicModel("mydb", tableName: "Posts");
//grab all the posts
var posts = table.All();
ViewData["Posts"] = posts;
return View();
}
这部分效果很好。但我该怎么做呢?
return View(posts);
如果我在 View 中引用 @posts.PostID
,它会出错并说它无效。因此,我尝试针对 DynamicModel 创建强类型 View ,但 posts
仍然不存在。
我知道我可以创建一个 ViewModel 并针对它键入 View ,然后将我的数据插入其中。这更多是关于了解 Controller / View 如何交互。
谢谢!
最佳答案
首先你需要创建一个类。例如:
public class Post : DynamicModel
{
public Post(): base("db")
{
PrimaryKeyField = "PostID";
}
}
在 Controller 中你可以有:
public ActionResult Index()
{
var table = new Post();
var posts = table.All();
return View(posts);
}
因此您可以创建强类型 View 并将 View 的模型设置为 IEnumerable。 View 将是这样的:
@model IEnumerable<dynamic>
<h2>Index</h2>
<ul>
@foreach (var item in Model)
{
<li>@item.PostID</li>
}
</ul>
关于c# - 将大量列表传递给 MVC3 中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5485052/