asp.net - ASP.NET 使用 return RedirectToAction(" ", " ") 如何使用它重定向到 cshtml
问题描述
我找不到解释如何使用 REdirectToAction 进行重定向的可用教程。有人可以分享一个链接来解释使用它所需的所有步骤吗?我想我很难理解如何给出参数可以在参数中找到带有模型的 HTML 文件?还是控制器?我对他们的沟通方式非常迷茫。请有人帮忙。
解决方案
对于 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 将数据从控制器传输到视图页面。
更多详细信息,请参考以下文章:
MVC中return View()、return Redirect()、return RedirectToAction()和RedirectToRoute()的区别
推荐阅读
- mysql - 为什么 Master 上的 GTID 与 Slave 上的 GTID 不同,而两者都同步(MariaDB 10.5)?
- sql - 像 Hive 的 LATERAL VIEW STACK 这样的非透视数据的 Snowflake 替代方案是什么?
- javascript - 阿波罗客户端 offsetLimitPagination 不起作用
- javascript - 有没有办法访问我的响应错误消息?
- java - 如何通过maven在tomee应用程序中从源代码和静态负载构建java代理?
- ansible - ansible中的多个OR条件
- javascript - 如何显示最少输入 2 个字符的 Javascript 过滤器结果?
- angular - 找不到名称“列表”?(Ionic - Angular) 使用 ViewChild 时
- linux - 将docker容器内的进程绑定到linux中的特定网络接口
- excel - 如何使用应用程序将我的 Firebase 数据导出到 Excel 工作表中?