【发布时间】:2016-02-25 16:50:57
【问题描述】:
我已经为此绞尽脑汁很久了,现在我要听从专家的意见。我知道这个问题已经被问过并回答了好几次,但我似乎无法解决任何问题。这是场景:正如标题所说,我试图将一个列表从控制器传递到视图。我使用的 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
}
【问题讨论】:
-
您是初级开发人员并且已经在使用 MVC?不错。
-
不要使用
ViewData- 将您的方法更改为return View(locationlist );,并将视图更改为@model List<string> @foreach(var l in Model) { ...
标签: c# asp.net-mvc list view controller