我已经绞尽脑汁想通过这种方式来延长我现在要推迟到专家。我知道这个问题已被问及几次回答,但我似乎无法得到任何工作。这是场景:正如标题所说,我试图从控制器传递一个列表到视图。我使用的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(模型中的变量){...' –