从控制器传递通用列表以查看mvc

时间:2016-02-25 16:50:58

标签: c# asp.net-mvc list view controller

我已经把我的大脑绞尽脑汁,以便我很快就会向专家推迟。我知道这个问题已被多次提出并回答,但我似乎无法完成任何工作。这是场景:正如标题所示,我试图将控制器中的列表传递给视图。我使用的API有一个基类型为"GetInventoryLocations"的方法List<string>。在下面的示例中,我实例化一个新列表并使用foreach循环遍历"InventoryLocation"以编程方式将集合中的每个项目转换为字符串并将其添加到我创建的列表"locationlist"中。最后,我将列表分配给viewdata。从那里我在视图中尝试了各种各样的东西,但仍然无法让它发挥作用。谢谢你的帮助。善待初级开发人员。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Moraware.JobTrackerAPI4;
using Evolveware1_0.Models;

namespace Evolveware1_0.Controllers
{
    [Authorize]
    public class InventoryController : Controller
    {

        //./Inventory/Locations
        [HttpGet]
        public ActionResult Index()
        {
            //declare variables for connection string to JobTracker API Service
            var DB = "databasename"; // your DB name here
            var JTURL = "https://" + DB + ".somecompany.net/" + DB + "/";
            var UID = "****"; // your UID here - needs to be an administrator or have the API role
            var PWD = "password"; // your PWD here

            //connect to API
            Connection conn = new Connection(JTURL + "api.aspx", UID, PWD);
            conn.Connect();
            //declaring the jobtracker list (type List<InventoryLocation>)
            var locs = conn.GetInventoryLocations();
            //create a new instance of the strongly typed List<string> from InventoryViewModels
            List<string> locationlist = new List<string>();
            foreach (InventoryLocation l in locs) {
                locationlist.Add(l.ToString());                  
            };
            ViewData["LocationsList"] = locationlist;

            return View();
        }//end ActionResult
    }

};

在视图中:

@using Evolveware1_0.Models
@using Evolveware1_0.Controllers
@*@model Evolveware1_0.Models.GetLocations*@

@using Evolveware1_0.Models;
@{
    ViewBag.Title = "Index";
}


<h2>Locations</h2>

@foreach (string l in ViewData["LocationList"].ToString())
{
    @l
}

1 个答案:

答案 0 :(得分:0)

您正在对列表执行toString(),这不起作用。您需要将ViewData转换为正确的类型,即InventoryLocation列表。

由于您使用的是Razor和MVC,我建议使用ViewBag,不需要进行强制转换。

在您的控制器而不是ViewData [&#34; LocationList&#34;] = locationlist中,初始化ViewBag属性以传递给您的视图。

ViewBag.LocationList = locationlist;

然后在你的循环视图中,只需访问ViewBag.LocationList对象。

@foreach (string l in ViewBag.Locationlist)
{
    @l
}