2016-02-25 112 views
1

我已经绞尽脑汁想通过这种方式来延长我现在要推迟到专家。我知道这个问题已被问及几次回答,但我似乎无法得到任何工作。这是场景:正如标题所说,我试图从控制器传递一个列表到视图。我使用的API有一个方法,"GetInventoryLocations",其基类型为List<string>。在下面的示例中,我实例化一个新列表,并使用foreach以编程方式将集合中的每个项目转换为字符串并将其添加到我创建的列表"locationlist"中,以循环遍历"InventoryLocation"。最后,我将该列表分配给viewdata。从那里我尝试了各种各样的东西,但仍然无法实现。谢谢你的帮助。对一位初级开发人员表示友善。从控制器传递一个通用列表来查看mvc

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 
} 
+0

您是初级开发人员,您已经使用MVC?尼斯。 – Brandon

+0

不要使用'ViewData' - 改变你的方法到'return View(locationlist);'和视图到'@model列表 @foreach(模型中的变量){...' –

回答

0

你正在做一个toString()到一个列表,这是不行的。您需要将您的ViewData转换为适当的类型,一个InventoryLocation列表。

由于您正在使用Razor和MVC,我建议使用ViewBag代替,不需要强制转换。

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

ViewBag.LocationList = locationlist; 

然后在您的循环中查看您的ViewBag.LocationList对象。

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

刚刚意识到我从来没有谢谢你回答这个问题。我很感激。 – SnowballsChance

相关问题