網站首頁 編程語言 正文
有這樣的一個需求:提交表單,如果用戶沒有登錄,就跳轉到登錄頁,登錄后,跳轉到原先表單提交這個頁面,而且需要保持提交表單界面的數據。
提交表單的頁面是一個強類型視圖頁,如果不考慮需要保持提交表單界面的數據,可以先設計這樣的一個Model:
public class Student { public string Name{get;set;} public string ReturnUrl{get;set;} }
在提交表單的視圖頁,大致這么寫:
@using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.Hidden("ReturnUrl", Request.Url.PathAndQuery) @Html.TextBoxFor(m => m.Name) <input type="submit" value="提交"/> }
在控制器中大致這么寫:
public ActionResult Index() { return View(new Student()); } [HttpPost] public ActionResult Index(Student student) { return Redirect(student.ReturnUrl); }
可是,雖然回到了表單提交的強類型視圖頁,表單數據卻沒有得以保持。
于是,想到了使用如下方式:
return View("someview", somemodel);
someview的名稱如何獲取呢?
public ActionResult Index() { return View(new Student()); }
以上,如果我們獲取到action的名稱就相當于獲取到視圖的名稱!
重新設計Model:
public class Student { public string Name { get; set; } public string ControllerName { get; set; } public string ActionName { get; set; } }
可以先從路由中把action名稱拿到,然后賦值給Student的ActionName屬性。
public class HomeController : Controller { public ActionResult Index() { Student student = new Student() { ActionName = this.ControllerContext.RouteData.Values["action"].ToString(), ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString() }; return View(student); } [HttpPost] public ActionResult Index(Student student) { ViewBag.msg = "我又回來了~~"; //如果是登錄,先驗證,驗證成功執(zhí)行下面的代碼 return View(student.ActionName, student); } }
以上,student.ActionName值既是action名稱也是view名稱。
在提交表單的強類型視圖頁:
@model MvcApplication1.Models.Student @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> <div>@ViewBag.msg</div> @using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.TextBoxFor(m => m.Name) <input type="submit" value="提交"/> }
所以,面對本篇開始描述的需求,僅僅跳轉是不夠的,需要向某個視圖傳遞Model,而其中的關鍵是:
1、從路由中獲取action名稱
2、action名稱和view名稱一致?
原文鏈接:https://www.cnblogs.com/darrenji/p/4246910.html
相關推薦
- 2022-05-26 Flutter自定義年月日倒計時_Android
- 2022-08-25 C/C++內存管理基礎與面試_C 語言
- 2022-09-01 Django定時任務Django-crontab的使用詳解_python
- 2024-03-13 微信小程序登錄接口 偶發(fā)性 解密錯誤
- 2021-12-08 .net?core?api接口JWT方式認證Token_實用技巧
- 2022-11-11 C#中ArrayList?類的使用詳解_C#教程
- 2022-03-20 Redis實現分布式鎖方法(redis分布式鎖的實現原理)
- 2022-10-18 EasyUI使用DataGrid實現動態(tài)列數據綁定_jquery
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支