从控制器传递泛型列表以查看 mvc

本文关键字:mvc 列表 泛型 控制器 | 更新日期: 2023-09-27 18:36:16

我已经为此绞尽脑汁了很长时间,现在我正在服从专家。我知道这个问题已经被问了好几次,但我似乎无法得到任何东西。场景如下:如标题所述,我正在尝试将列表从控制器传递到视图。我正在使用具有方法的 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

你正在对列表执行 toString(),这将不起作用。您需要将 ViewData 转换为其正确的类型,即 InventoryLocation 列表。

由于您使用的是Razor和MVC,我建议使用ViewBag,无需转换。

在控制器中,而不是 ViewData["位置列表"] = 位置列表中,初始化要传递给视图的 ViewBag 属性。

ViewBag.LocationList = locationlist;

然后在循环中的视图中,只需访问ViewBag.LocationList对象即可。

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