国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

ASP.NET MVC實現(xiàn)登錄后跳轉(zhuǎn)到原界面

瀏覽:29日期:2022-06-08 10:43:48

有這樣的一個需求:提交表單,如果用戶沒有登錄,就跳轉(zhuǎn)到登錄頁,登錄后,跳轉(zhuǎn)到原先表單提交這個頁面,而且需要保持提交表單界面的數(shù)據(jù)。

提交表單的頁面是一個強類型視圖頁,如果不考慮需要保持提交表單界面的數(shù)據(jù),可以先設(shè)計這樣的一個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);
}

可是,雖然回到了表單提交的強類型視圖頁,表單數(shù)據(jù)卻沒有得以保持。

于是,想到了使用如下方式:

return View("someview", somemodel);

someview的名稱如何獲取呢?

public ActionResult Index()
{
    return View(new Student());
}

以上,如果我們獲取到action的名稱就相當于獲取到視圖的名稱!

重新設(shè)計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="提交"/>
}

所以,面對本篇開始描述的需求,僅僅跳轉(zhuǎn)是不夠的,需要向某個視圖傳遞Model,而其中的關(guān)鍵是:
1、從路由中獲取action名稱
2、action名稱和view名稱一致 

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接

標簽: ASP.NET
相關(guān)文章:
主站蜘蛛池模板: 齐齐哈尔市| 蓬莱市| 卓资县| 三门县| 德安县| 依安县| 海门市| 翁牛特旗| 柏乡县| 延长县| 临西县| 鄢陵县| 元阳县| 久治县| 沽源县| 南城县| 元阳县| 崇礼县| 巩义市| 珠海市| 志丹县| 绵竹市| 西城区| 酉阳| 布尔津县| 四平市| 肃南| 甘洛县| 海宁市| 科技| 右玉县| 当阳市| 文水县| 无极县| 永丰县| 元阳县| 海原县| 西丰县| 胶州市| 左贡县| 阿勒泰市|