ASP.NET MVC实现登录后跳转到原界面

Erin ·
更新时间:2024-09-20
· 696 次阅读

有这样的一个需求:提交表单,如果用户没有登录,就跳转到登录页,登录后,跳转到原先表单提交这个页面,而且需要保持提交表单界面的数据。

提交表单的页面是一个强类型视图页,如果不考虑需要保持提交表单界面的数据,可以先设计这样的一个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 = "我又回来了~~"; //如果是登录,先验证,验证成功执行下面的代码 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名称一致 

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对软件开发网的支持。如果你想了解更多相关内容请查看下面相关链接



net ASP.NET 界面 MVC ASP

需要 登录 后方可回复, 如果你还没有账号请 注册新账号