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

不打扰是莪最后的温柔 提交于 2019-11-26 21:49:02

问题


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


回答1:


You need to cast in the View

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



回答2:


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.




回答3:


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>


来源:https://stackoverflow.com/questions/1405383/asp-net-mvc-how-to-pass-an-array-to-the-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!