asp.net - 如何将模型和附加参数从视图传递到控制器
问题描述
在我看来,使用 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; }
}
解决方案
您不应该这样存储data = Model
会导致性能和安全问题。
您只需fileToDownload
从 View 中存储一个值。之后,在 Controller 中,您应该通过fileToDownload
参数获取文件。
[HttpPost]
public ActionResult DownloadFile(string fileToDownload)
{
// download the file by `fileToDownload` param here
return RedirectToAction("Index");
}
推荐阅读
- android - 在真机上运行时,Android 应用程序图标背景颜色不同
- python - 如何在 Keras 中使用 CNN 处理多标签分类的不平衡数据?
- java - 如何在杰克逊显式更改编码?
- android - 将意图传递给 MainActivity 时出现 NullPointerException TextView setonClickListener
- jquery - 将数组传递给 jQuery 每个函数以重新格式化数据
- ios - Swift - 带有动画的可拖动 UIView
- python - 添加 2 个不同等级的张量
- spring-boot - 如何在 SpringBoot:RabbitMQ 中为每个队列配置一个消费者?
- php - woocommerce 产品的自定义 WP 查询
- asp.net-mvc - 如何使用 j 查询找到切换复选框是否选中按钮单击