【问题标题】:Pass a generic list from controller to view mvc从控制器传递一个通用列表以查看 mvc
【发布时间】: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&lt;string&gt; @foreach(var l in Model) { ...

标签: c# asp.net-mvc list view controller


【解决方案1】:

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

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

在您的控制器中,而不是 ViewData["LocationList"] = locationlist,初始化一个 ViewBag 属性以传递给您的视图。

ViewBag.LocationList = locationlist;

然后在您的循环视图中访问您的 ViewBag.LocationList 对象。

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

【讨论】:

  • 刚刚意识到我从来没有感谢你回答这个问题。我很感激。
猜你喜欢
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多