我已經絞盡腦汁想通過這種方式來延長我現在要推遲到專家。我知道這個問題已被問及幾次回答,但我似乎無法得到任何工作。這是場景:正如標題所說,我試圖從控制器傳遞一個列表到視圖。我使用的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
}
您是初級開發人員,您已經使用MVC?尼斯。 – Brandon
不要使用'ViewData' - 改變你的方法到'return View(locationlist);'和視圖到'@model列表 @foreach(模型中的變量){...' –