首页 > 解决方案 > 如何将模型和附加参数从视图传递到控制器

问题描述

在我看来,使用 ASP.NET MVC,我列出了一些文件并将它们显示为一个按钮。通过单击每个按钮,应下载相应的文件。

为了显示文件列表,我将模型传递给查看,当用户单击每个按钮时,我必须将文件名和原始模型发送回控制器。

我找到了类似问题的答案,但就我而言,我没有一个按钮。我在视图中呈现的每个文件名都有一个按钮。

这是我的观点的代码:

@using (Html.BeginForm("DownloadFile", "SharedFolder", FormMethod.Post))
{
    <div class="col-sm-6">
        <div class="panel panel-info">
            <div class="panel-heading">Files</div>
            <div class="panel-body" style="max-height:300px; height:300px; overflow-y:scroll">
                @foreach (var file in Model.Files)
                {
                    <button type="button" class="btn btn-link btn-sm" onclick="location.href='@Url.Action("DownloadFile", "SharedFolder", new { fileToDownload = file, data = Model })'">
                        <div class="glyphicon glyphicon-file" style="color:dodgerblue">
                            <span style="color:black;">@file</span>
                        </div>
                    </button>
                    <br />
                }
            </div>
        </div>
    </div>
}

我的控制器动作:

    [HttpPost]
    public ActionResult DownloadFile(string fileToDownload, FolderExplorerViewModel data)
    {
        // download the file and return Index view
        return RedirectToAction("Index");
    }

当我单击文件下载时,出现以下错误:

无法找到该资源。

请求的 URL:/SharedFolder/DownloadFile

更新:

这是我的视图模型

public class FolderExplorerViewModel
{
    public int ID { get; set; }
    public List<Folder> Folders { get; set; }
    public List<string> Files { get; set; }
    public string SelectedPath { get; set; }
}

标签: asp.netasp.net-mvcasp.net-mvc-5

解决方案


您不应该这样存储data = Model会导致性能和安全问题。

您只需fileToDownload从 View 中存储一个值。之后,在 Controller 中,您应该通过fileToDownload参数获取文件。

[HttpPost]
public ActionResult DownloadFile(string fileToDownload)
{
    // download the file by `fileToDownload` param here

    return RedirectToAction("Index");
}

推荐阅读