在 MVC 中以单个方法返回视图 ASP.Net 文件

本文关键字:视图 ASP Net 文件 返回 方法 MVC 单个 | 更新日期: 2023-09-27 18:35:48

我正在 ASP.Net MVC中构建一个应用程序,并希望返回一个View并向用户提供下载。可能吗?现在,我可以使用

return View();

使用以下方法提供文件下载:

return File(FilePath, "text", "downloadFileName");

原因:将有一个复选框指示"如果下载文件"。如果选中,单击按钮后,指定的内容将显示在屏幕上,并出现下载对话框。

任何帮助不胜感激!

更新:最后,我选择在返回的View中提供一个下载链接,现在适用于该应用程序。

在 MVC 中以单个方法返回视图 ASP.Net 文件

请像下面这样使用。

ViewData["text"] = "text that you need to return";
ViewData["FileName"] = "Name of the file that you need to return";
ViewData["Filepath"] = "Path of the file that you need to return";
return View();

在您看来,您可以像下面这样使用它们

@{
    var text = ViewData["text"];
    var filename = ViewData["FileName"];
    var filePath = ViewData["Filepath"];
}

如果您需要在不使用ViewData或ViewBage的情况下完成,请遵循以下代码。

需要为此执行3个步骤。

第 1 步: 为其创建一个模型类。我的型号代码

public class FileDetails
{
    public string Text { get; set; }
    public string FileName { get; set; }
    public string Filepath { get; set; }
}

第 2 步:控制器代码以返回带有文件详细信息模型的视图。

FileDetails Details = new FileDetails();
Details.Text = "text that you need to return";
Details.FileName = "Name of the file that you need to return";
Details.Filepath = "Path of the file that you need to return";
return View("ViewName", Details);

第 3 步:您的视图必须包含文件详细信息模型标题。

@model YourProjectName.Models.FileDetails

上面的代码必须位于您需要使用这些详细信息的视图页面顶部。

我的视图代码

@{
    var text = Model.Text;
    var filename = Model.FileName;
    var filePath = Model.Filepath;
}