回転---ASP.NET MVCではログインを実現して元の画面に戻る

4397 ワード

フォームをコミットし、ユーザーがログインしていない場合はログインページにジャンプし、ログイン後、元のフォームにジャンプしてこのページをコミットし、フォームインタフェースのデータを保持する必要があります.
 
フォームをコミットするページは強力なタイプのビューページです.フォームインタフェースをコミットする必要があるデータを考慮しない場合は、まずこのようなモデルを設計します.
 
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名が一致することである.