【问题标题】:Passing an array or list of strings from one action to another when redirecting重定向时将数组或字符串列表从一个动作传递到另一个动作
【发布时间】:2011-11-10 00:51:26
【问题描述】:

我有一个帖子操作导入:

public ActionResult Import()
{
    var fileNames = new List<String>();

    foreach (string path in Directory.GetFiles(directoryPath))
    {
        //do a whole bunch of stuff
        ...
        fileNames.Add(path.Split('\\').Last());            
    }

    return RedirectToAction("Index", new { InvalidFiles = fileNames });
}

如您所见,它重定向到 Index 操作,传递文件名的 List&lt;String&gt;

public ActionResult Index(List<String> InvalidFiles)
{
    return View();
}

Index 操作中,List 包含适量的元素,但所有实际字符串已从文件名更改为字符串“System.Collections.Generic.List`1[System.String] ”。

知道为什么会这样吗?是否有更好的方法将列表传递给新操作,可能使用 TempData?

【问题讨论】:

    标签: .net asp.net-mvc


    【解决方案1】:

    您可以使用TempData 在操作之间临时保存数据。

    public ActionResult Import()
    {
        var fileNames = new List<String>();
    
        foreach (string path in Directory.GetFiles(directoryPath))
        {
            //do a whole bunch of stuff
            ...
            fileNames.Add(path.Split('\\').Last());            
        }
    
        TempData["fileNames"] = fileNames;
    
        return RedirectToAction("Index");
    }
    
    
    public ActionResult Index()
    {
        var invalidFiles = TempData["fileNames"] as List<String>;
    
        return View();
    }
    

    【讨论】:

    • 是的,我想通了。知道为什么我的原始方法会产生如此奇怪的结果吗?
    • @link664 那是因为 MVC 调用了ToString() 方法来产生路由值。查询字符串是一个键值对列表。因此,您不能使用查询字符串发送List&lt;String&gt;
    猜你喜欢
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    相关资源
    最近更新 更多