将List <string>从控制器传递到View ASP.NET(null引用)

时间:2015-05-24 15:39:00

标签: c# asp.net nullreferenceexception

我上课了。在这个类中,我想列出文件夹中的.txt文件的名称,并将它们保存到List<string>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace Aplikacja.Models
{
    public class Lists
    {
        public List<string> ListFiles()
        {
            DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Kamm\Documents\ASP.NET\");
            FileInfo[] files = dir.GetFiles("*.txt");
            string str = "";
            List<string> allfiles = new List<string>();

            foreach(FileInfo file in files)
            {
                str = file.Name;
                allfiles.Add(str);
            }

            return allfiles;
        }
    }
}

然后,我有一个Controller将值放入List中以将其传递给View:

[HttpPost]
public ActionResult Index(string listButton)
{
    if (listButton != null)
    {
        var list = new Lists();
        list.ListFiles();
        var names = new List<string>();
        names = list.ListFiles();
        ViewBag.List = names;
        return View();
     }
}

我有一个视图来填充列表:

<button value="List" name="listButton" type="submit" class="btn btn-primary" formmethod="post">List</button>
<ul>
    @foreach (var item in (List<string>)ViewBag.List){
        <span>
            @item
        </span>
    }
</ul>

但是当我启动应用时,我遇到了错误:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 12:     <button value="List" name="listButton" type="submit" class="btn btn-primary" formmethod="post">List</button>
Line 13:     <ul>
Line 14:         @foreach (var item in (List<string>)ViewBag.List){
Line 15:             <span>
Line 16:                 @item


Source File: c:\Users\Kamm\Documents\ASP.NET\Aplikacja\Aplikacja\Aplikacja\Views\Home\Index.cshtml    Line: 14 

有人能帮助我吗?我不知道该怎么做,即使我想从Controller传递一个简单的List也有同样的错误。

解决! 我在View中添加了一行:

@if ((List<string>)ViewBag.List != null)

应用程序启动时可能出现问题..

3 个答案:

答案 0 :(得分:1)

您的代码存在很多问题,但是您获得该异常的原因是您没有在控制器的HTTP GET操作中将文件名列表添加到VieBag,而是尝试在HTTP POST中执行此操作行动。

在您的索引操作方法上将 [HttpPost] 更改为 [HttpGet] ,或者只删除该属性(默认情况下,控制器中的每个操作都是HttpGet,除非您使用其他操作标记它属性),它会工作。

[HttpGet]
public ActionResult Index()
{
    var lists = new Lists();
    var names = lists.ListFiles();

    ViewBag.List = names;

    return View();
}

但是,更清晰的解决方案是强烈输入您的视图并从操作方法返回文件名列表。

答案 1 :(得分:0)

在控制器中使用: 返回视图(名称);

在您的视图顶部包含您要发送的模型:

@model List

在循环中使用:

@foreach(模型中的var项目)......

答案 2 :(得分:0)

始终检查对象是否为空。

下面;检查ViewBag.List是否为null。 你可以在后面或你发现的时候做代码 @if((List)ViewBag.List!= null)

相关问题