久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

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

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

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

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

提交表單的頁(yè)面是一個(gè)強(qiáng)類(lèi)型視圖頁(yè),如果不考慮需要保持提交表單界面的數(shù)據(jù),可以先設(shè)計(jì)這樣的一個(gè)Model:

public class Student
{
    public string Name{get;set;}
    public string ReturnUrl{get;set;}
}

在提交表單的視圖頁(yè),大致這么寫(xiě):

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.Hidden("ReturnUrl", Request.Url.PathAndQuery)
    @Html.TextBoxFor(m => m.Name)
    <input type="submit" value="提交"/>
}

在控制器中大致這么寫(xiě):

public ActionResult Index()
{
    return View(new Student());
}
[HttpPost]
public ActionResult Index(Student student)
{
    return Redirect(student.ReturnUrl);
}

可是,雖然回到了表單提交的強(qiáng)類(lèi)型視圖頁(yè),表單數(shù)據(jù)卻沒(méi)有得以保持。

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

return View("someview", somemodel);

someview的名稱(chēng)如何獲取呢?

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

以上,如果我們獲取到action的名稱(chēng)就相當(dāng)于獲取到視圖的名稱(chēng)!

重新設(shè)計(jì)Model:

    public class Student
    {
public string Name { get; set; }
public string ControllerName { get; set; }
public string ActionName { get; set; }
    }

可以先從路由中把a(bǔ)ction名稱(chēng)拿到,然后賦值給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 = "我又回來(lái)了~~";
    //如果是登錄,先驗(yàn)證,驗(yàn)證成功執(zhí)行下面的代碼
    return View(student.ActionName, student);
}
    }

以上,student.ActionName值既是action名稱(chēng)也是view名稱(chēng)。

在提交表單的強(qiáng)類(lèi)型視圖頁(yè):

@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="提交"/>
}

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

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

標(biāo)簽: ASP.NET
相關(guān)文章:
主站蜘蛛池模板: 苍山县| 桂林市| 唐海县| 松桃| 阿勒泰市| 鄂托克旗| 育儿| 巴林右旗| 温泉县| 新宁县| 康平县| 西盟| 璧山县| 翁牛特旗| 容城县| 修水县| 惠州市| 新民市| 洪泽县| 亚东县| 石泉县| 舞钢市| 哈密市| 博野县| 渑池县| 张家界市| 滦南县| 盘锦市| 公主岭市| 青阳县| 潜山县| 淮南市| 乌鲁木齐县| 区。| 酒泉市| 余江县| 双柏县| 恩施市| 梨树县| 象州县| 宁阳县|