下载文件后如何重定向ASP.NET核心MVC部分视图

下载文件后如何重定向ASP.NET核心MVC部分视图,asp.net,asp.net-mvc,asp.net-core-mvc,partial-views,Asp.net,Asp.net Mvc,Asp.net Core Mvc,Partial Views,我有一个名为ExportPagePartial的asp.net核心MVC局部视图,允许用户从系统导出页面并下载。在HttpGet控制器操作中,我将局部视图显示为模式弹出窗口,以获取用户输入 模态弹出窗口 一旦用户从模式弹出部分视图(表单提交操作)中点击导出按钮,将正确调用以下HTTPPost操作。 在此操作中,我必须从Web Api获取文件,然后通过浏览器下载,但是在下载完成后,我希望关闭部分视图。下载完成后,部分视图仍然可见 返回操作永远不起作用,部分模式弹出视图也不会关闭 返回Redirec

我有一个名为ExportPagePartial的asp.net核心MVC局部视图,允许用户从系统导出页面并下载。在HttpGet控制器操作中,我将局部视图显示为模式弹出窗口,以获取用户输入

模态弹出窗口

一旦用户从模式弹出部分视图(表单提交操作)中点击导出按钮,将正确调用以下HTTPPost操作。 在此操作中,我必须从Web Api获取文件,然后通过浏览器下载,但是在下载完成后,我希望关闭部分视图。下载完成后,部分视图仍然可见

返回操作永远不起作用,部分模式弹出视图也不会关闭 返回RedirectToActionnameofBlahRedirectAction

fileContent.ExecuteSultAsyncActionContext

这是因为在下载文件时,ExportPagePartial已确定返回流,并且不会执行重定向操作

我建议您将触发ExportPagePartial的post方法更改为ajax来实现,这样您就可以成功地执行ExportPagePartial,并在该方法之后,将页面重定向到js中所需的位置

以下是基于您的代码的我的演示的完整代码:

  public class ExportTestController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public IActionResult ExportPagePartial(string userId, string businessAccountId, string projectId, string pageId)
        {
            ExportPageViewModel model = new ExportPageViewModel()
            {
                Id = 1,
                Gender = "male",
                Name = "aaa",
                Number = "1231244"
            };
            return PartialView(nameof(ExportPagePartial), model);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ExportPagePartial(ExportPageViewModel model)
        {
            // Call Web API to get the file              
            string downloadUrl = "blah_blah_url";

              using (HttpResponseMessage httpResponse = await WebApiClient.HttpClient.PostAsJsonAsync(downloadUrl, unprotectedExportInput))
                {
                    if (!httpResponse.IsSuccessStatusCode)
                    {
                        throw new InvalidOperationException(await httpResponse.Content.ReadAsStringAsync());
                    }

                    // Download the file now.
                    ActionContext actionContext = new ActionContext(HttpContext, ControllerContext.RouteData, ControllerContext.ActionDescriptor, ModelState);
                    FileStreamResult fileContent = File(await httpResponse.Content.ReadAsStreamAsync(), httpResponse.Content.Headers.ContentType.MediaType, httpResponse.Content.Headers.ContentDisposition.FileName);
                    await fileContent.ExecuteResultAsync(actionContext);
                }

            // Redirect to main pain
            // The view never redirects and partial view is still visible
            return RedirectToAction(nameof(BlahRedirectAction));
        }
Index.cshtml:

@{
    ViewData["Title"] = "Index";
    Layout = null;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
    $(function () {
        $("a").click(function () {
            var route = $(this).attr("href");
            $('#partial').load(route);
        })

        $("form").submit(function () {
            $.ajax({
                url: $("form").attr('action'),
                type: 'Post',
                data: $("form").serializeArray(),
                success: function () {
                    //$("#ModalPlaceholder").hide();
                    window.location.href = "/ExportTest/BlahRedirectAction";
                }
            });
        })
    })

</script>
<a class="dropdown-item" asp-action="ExportPagePartial"
   asp-route-userId="1" asp-route-businessAccountId="1"
   asp-route-projectId="1" asp-route-pageId="1"
   data-toggle="modal" data-target="#ModalPlaceholder" title="Export page."><i class="fas fa-cloud-download-alt"></i> &nbsp; Export</a>

<div class="modal fade" id="ModalPlaceholder" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <form asp-action="ExportPagePartial" method="post">
        <div id="partial">
        </div>
    </form>
</div>
ExportPagePartial.cshtml:

@model ExportPageViewModel
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label asp-for="Id" class="control-label">@Model.Id</label>
                <input asp-for="Id" class="form-control" hidden />
            </div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Gender" class="control-label"></label>
                <input asp-for="Gender" class="form-control" />
                <span asp-validation-for="Gender" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Number" class="control-label"></label>
                <input asp-for="Number" class="form-control" />
                <span asp-validation-for="Number" class="text-danger"></span>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary" >Save changes</button>
        </div>
    </div>
</div> 
以下是测试结果:


您的局部视图以何种形式呈现,类似于模态弹出窗口?你能提供全面的代码供我们参考吗?@YongqingYu是的,局部视图显示为模态弹出窗口,我更新了描述以包含更多细节。
  public class ExportTestController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public IActionResult ExportPagePartial(string userId, string businessAccountId, string projectId, string pageId)
        {
            ExportPageViewModel model = new ExportPageViewModel()
            {
                Id = 1,
                Gender = "male",
                Name = "aaa",
                Number = "1231244"
            };
            return PartialView(nameof(ExportPagePartial), model);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ExportPagePartial(ExportPageViewModel model)
        {
            // Call Web API to get the file              
            string downloadUrl = "blah_blah_url";

              using (HttpResponseMessage httpResponse = await WebApiClient.HttpClient.PostAsJsonAsync(downloadUrl, unprotectedExportInput))
                {
                    if (!httpResponse.IsSuccessStatusCode)
                    {
                        throw new InvalidOperationException(await httpResponse.Content.ReadAsStringAsync());
                    }

                    // Download the file now.
                    ActionContext actionContext = new ActionContext(HttpContext, ControllerContext.RouteData, ControllerContext.ActionDescriptor, ModelState);
                    FileStreamResult fileContent = File(await httpResponse.Content.ReadAsStreamAsync(), httpResponse.Content.Headers.ContentType.MediaType, httpResponse.Content.Headers.ContentDisposition.FileName);
                    await fileContent.ExecuteResultAsync(actionContext);
                }

            // Redirect to main pain
            // The view never redirects and partial view is still visible
            return RedirectToAction(nameof(BlahRedirectAction));
        }
@{
    ViewData["Title"] = "Index";
    Layout = null;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
    $(function () {
        $("a").click(function () {
            var route = $(this).attr("href");
            $('#partial').load(route);
        })

        $("form").submit(function () {
            $.ajax({
                url: $("form").attr('action'),
                type: 'Post',
                data: $("form").serializeArray(),
                success: function () {
                    //$("#ModalPlaceholder").hide();
                    window.location.href = "/ExportTest/BlahRedirectAction";
                }
            });
        })
    })

</script>
<a class="dropdown-item" asp-action="ExportPagePartial"
   asp-route-userId="1" asp-route-businessAccountId="1"
   asp-route-projectId="1" asp-route-pageId="1"
   data-toggle="modal" data-target="#ModalPlaceholder" title="Export page."><i class="fas fa-cloud-download-alt"></i> &nbsp; Export</a>

<div class="modal fade" id="ModalPlaceholder" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <form asp-action="ExportPagePartial" method="post">
        <div id="partial">
        </div>
    </form>
</div>
@model ExportPageViewModel
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label asp-for="Id" class="control-label">@Model.Id</label>
                <input asp-for="Id" class="form-control" hidden />
            </div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Gender" class="control-label"></label>
                <input asp-for="Gender" class="form-control" />
                <span asp-validation-for="Gender" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Number" class="control-label"></label>
                <input asp-for="Number" class="form-control" />
                <span asp-validation-for="Number" class="text-danger"></span>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary" >Save changes</button>
        </div>
    </div>
</div>