.Net Core MVC 如何记录用户多步视图跳转选择的路径并展示
实现方案
核心逻辑是持久化用户每一步的选择,推荐用Session存储,不需要在页面间反复传递历史参数,实现最简单。
1. 控制器代码示例
假设你的控制器名为SelectionController,4个Action对应4个步骤:
public class SelectionController : Controller { // 第一步视图 public ActionResult Step1() { // 进入第一步时清空历史选择,避免旧数据干扰 Session["UserSelectPath"] = new List<int>(); return View(); } // 第二步视图,接收第一步传递的ID public ActionResult Step2(int id) { var path = Session["UserSelectPath"] as List<int> ?? new List<int>(); // 校验:如果未经过第一步选择,直接跳转回第一步 if (path.Count == 0) { path.Add(id); Session["UserSelectPath"] = path; return View(); } return RedirectToAction("Step1"); } // 第三步视图,接收第二步传递的ID public ActionResult Step3(int id) { var path = Session["UserSelectPath"] as List<int> ?? new List<int>(); if (path.Count == 1) { path.Add(id); Session["UserSelectPath"] = path; return View(); } return RedirectToAction("Step1"); } // 第四步结果视图,接收第三步传递的ID,展示完整路径 public ActionResult Result(int id) { var path = Session["UserSelectPath"] as List<int> ?? new List<int>(); if (path.Count == 2) { path.Add(id); ViewBag.FinalPath = string.Join(", ", path); // 展示完可以按需清空Session // Session.Remove("UserSelectPath"); return View(); } return RedirectToAction("Step1"); } }
2. 视图代码示例
Step1.cshtml(第一步视图)
三个按钮点击后跳转到第二步,携带对应ID:
<div> @Html.ActionLink("Button11", "Step2", new { id = 11 }, new { @class = "btn" }) @Html.ActionLink("Button12", "Step2", new { id = 12 }, new { @class = "btn" }) @Html.ActionLink("Button13", "Step2", new { id = 13 }, new { @class = "btn" }) </div>
Step2.cshtml(第二步视图)
三个按钮点击后跳转到第三步,携带对应ID:
<div> @Html.ActionLink("Button21", "Step3", new { id = 21 }, new { @class = "btn" }) @Html.ActionLink("Button22", "Step3", new { id = 22 }, new { @class = "btn" }) @Html.ActionLink("Button23", "Step3", new { id = 23 }, new { @class = "btn" }) </div>
Step3.cshtml(第三步视图)
三个按钮点击后跳转到结果页,携带对应ID:
<div> @Html.ActionLink("Button31", "Result", new { id = 31 }, new { @class = "btn" }) @Html.ActionLink("Button32", "Result", new { id = 32 }, new { @class = "btn" }) @Html.ActionLink("Button33", "Result", new { id = 33 }, new { @class = "btn" }) </div>
Result.cshtml(结果视图)
展示完整选择路径:
<p>你的选择路径为:@ViewBag.FinalPath</p>
替代方案(不依赖Session)
如果不想用Session,也可以把历史选择通过QueryString串联传递,比如第二步的按钮跳转链接构造为/Selection/Step3?id=21&preId=11,第三步的跳转链接构造为/Selection/Result?id=31&preId1=11&preId2=21,最后在结果页拼接所有参数即可,好处是不依赖服务端Session,用户刷新页面不会丢失选择。
内容的提问来源于stack exchange,提问作者Pier Giordano
相关产品推荐
相关产品推荐

