首页 > 解决方案 > ASP.NET 使用 return RedirectToAction(" ", " ") 如何使用它重定向到 cshtml

问题描述

我找不到解释如何使用 REdirectToAction 进行重定向的可用教程。有人可以分享一个链接来解释使用它所需的所有步骤吗?我想我很难理解如何给出参数可以在参数中找到带有模型的 HTML 文件?还是控制器?我对他们的沟通方式非常迷茫。请有人帮忙。

标签: asp.netasp.net-core

解决方案


对于 RedirectToAction 方法,您可以检查ControllerBase.RedirectToAction Method。该方法用于根据动作名称重定向到指定的动作。

例如:如果 Home 控制器包含以下方法:

[HttpGet]
public IActionResult ProductIndex(int id)
{
    var product = RetrieveProduct(id);
    return View(product);
}

[HttpPost]
public IActionResult Product(int id, Product product)
{
    UpdateProduct(product);
    return RedirectToAction("ProductIndex","Home", new {id=101}); //the parameters: actionName, controllerName, and routeValues.
}

使用上面的代码,在调用 Product action 方法时,会重定向到 ProductIndex action 方法,并发送 id 参数。

如果你想重定向到一个特殊的视图,你可以使用View() 方法

例如,使用下面的代码,如果调用Test方法,会返回Privacy.cshtml视图页面,并将Student Object发送给视图。

    public IActionResult Test()
    {
        var student = new Student()
        {
            StudentId = 1001,
            StudentName = "Tom"
        };
        return View("~/Views/Home/Privacy.cshtml", student);
    }

Privacy.cshtml 中的代码:

@model netcore5.Models.Student
@{
    ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<div class="form-group">
    <label asp-for="StudentId" class="control-label"></label>
    <input asp-for="StudentId" class="form-control" />
</div>

<div class="form-group">
    <label asp-for="StudentName" class="control-label"></label>
    <input asp-for="StudentName" class="form-control" />
</div>

输出如下:

在此处输入图像描述

此外,您还可以使用 ViewBag 或 ViewData 将数据从控制器传输到视图页面。

更多详细信息,请参考以下文章:

ASP.NET Core MVC 中的视图

MVC中return View()、return Redirect()、return RedirectToAction()和RedirectToRoute()的区别


推荐阅读