ASP.NET MVC - 如何将数组传递给视图?
我在这里努力寻找一种简单的方法将数组从控制器传递到 ASP.NET MVC 框架上的视图。
所以在我的控制器中我会有类似的东西:
public class HomeController : ApplicationController
{
public ActionResult Index()
{
string[] myArray = { "value01", "value02", "value03"};
ViewData["passedArray"] = myArray;
return View();
}
}
所以在我看来我只需调用 ViewData["passedArray"] 并在其上运行一个循环。
但显然 ViewData 被视图作为 System.String 接收,可能是因为数组数据类型上的声明,但不幸的是我不知道如何传递它正确且简单,无需创建数百万行代码。
如果有人能帮助我,那就太好了。
提前致谢
I'm struggling myself here, to find a easy way to pass an array from the controller to the view on ASP.NET MVC framework.
so in my controller I would have something like:
public class HomeController : ApplicationController
{
public ActionResult Index()
{
string[] myArray = { "value01", "value02", "value03"};
ViewData["passedArray"] = myArray;
return View();
}
}
so in my view I would have just a call to ViewData["passedArray"] and run a loop on it.
But apparently the ViewData is being received by the view as System.String, probably because of the declaration on the Array DataType, but unfortunately I don't know how to pass it properly and simply without create millions of code lines.
It would be fantastic if one could help me.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在视图中投射
You need to cast in the View
这应该通过将视图中的 ViewData["passedArray"] 转换为 string[] 来实现。或者,如果您想更进一步:创建一个包含此数组作为成员的 ViewModel 类,并将该 ViewModel 传递给视图的强类型版本。
This should work by casting ViewData["passedArray"] within the view to string[]. Alternatively, if you want to go the extra mile: create a ViewModel class that contains this array as a member and pass that ViewModel to a strongly-typed version of your view.
您可以像这样使用 PartialView:
Controller
视图
You can use PartialView like this:
Controller
View