ASP.NET MVC - How to pass an Array to the view?

一笑奈何 提交于 2019-11-28 01:02:14
Daniel Elliott

You need to cast in the View

<% var myArray = (string[])ViewData["passedArray"]; %>

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.

You can use PartialView like this:

  • Controller

        public ActionResult Index()
        {
            List<string> arr = new List<string>() { "apple", "banana", "cat" };
            return View(arr);
        }
    
  • View

@model List<string>
@foreach (var item in Model) { 
        @Html.Partial("~/Views/Shared/Fruits/_myFruits.cshtml", item);
}
  • PatialView i.e. _myFruits.cshtml
@model  string
<li>@Model</li>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!