2016-02-25 116 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

相關問題