ASP.NET MVC 4(二)コントローラ

23247 ワード

MVCではコントローラが要求を処理し,それによってデータモデルを操作し,最後にユーザにビューを返す.
IControllerインタフェース
すべてのコントローラクラスはControllerで終わり、Systemを実現しなければならない.Web.Mvc.IControllerインタフェースで、最も簡単なコントローラクラスは次のとおりです.
public class BasicController : IController {

        public void Execute(RequestContext requestContext) {

            string controller = (string)requestContext.RouteData.Values["controller"];
            string action = (string)requestContext.RouteData.Values["action"];

            if (action.ToLower() == "redirect") {
                requestContext.HttpContext.Response.Redirect("/Derived/Index");
            } else {
                requestContext.HttpContext.Response.Write(
                    string.Format("Controller: {0}, Action: {1}", 
                    controller, action));
            }
        }
    }

BasicControllerクラスはIControllerの唯一の方法Execute()を実現し、上記の例では要求応答に直接データを返し、自分のニーズに応じて顧客要求を柔軟に処理することができます.
Controllerクラス
より多くの場合、MVCが定義した制御クラスSystemを直接継承します.Web.Mvc.Controller:
 public class DerivedController : Controller
    {

        public ActionResult Index()
        {
            ViewBag.Message = "Hello from the DerivedController Index method";
            return View("MyView");
        }

    }

ControllerクラスパッケージのIController.Execute()メソッドは、ここのIndex()など、定義したActionメソッドを呼び出します.Controllerは、関連データの入手を容易にするための多くのプロパティを提供しています.
  • Request:例えばRequest.QueryString、Request.Url、Request.Form、Request.HttpMethodなど.
  • Response:Responseに直接ユーザーにデータを返すことができます.
  • RouteData:ルートマッピングに関するデータ、例えばRouteData.Route、RouteData.Values.
  • HttpContext:例えばHttpContext.HttpSessionStateBAse、HttpContext.Items.
  • User:現在セッションが認証されているユーザー情報.
  • TempData:現在のユーザーの一時的な情報を保存し、Viewに渡すことができます.

  • Controllerデータの取得例:
    string userName = User.Identity.Name; 
    string serverName = Server.MachineName; 
    string clientIP = Request.UserHostAddress; 
    DateTime dateStamp = HttpContext.Timestamp; 
    AuditRequest(userName, serverName, clientIP, dateStamp, "Renaming product"); 
    // Retrieve posted data from Request.Form 
    string oldProductName = Request.Form["OldName"]; 
    string newProductName = Request.Form["NewName"]; 
    bool result = AttemptProductRename(oldProductName, newProductName); 
    ViewData["RenameResult"] = result; 
    return View("ProductRenamed"); 

    Actionメソッドパラメータ
    コントローラアクションメソッドには、次のような一連のパラメータがあります.
    ... 
    public ActionResult ShowWeatherForecast(string city, DateTime forDate) { 
    // ... implement weather forecast here ... 
    return View(); 
    } 
    ... 

    これらのパラメータはMVCのValue providersとmodel bindersによって提供され、MVCは要求データなどから自動的に名前でパラメータ値を解析し、タイプ変換を行います.例えば、上記の例のcityとforDateは以下のようになります.
    string city = (string)RouteData.Values["city"]; 
    DateTime forDate = DateTime.Parse(Request.Form["forDate"]); 

    レスポンス出力
    IcontrollerのExcecute()メソッドから直接応答を出力したり、ControllerでResponseを使用して直接応答を出力したりすることができます.
    public void ProduceOutput()
            {
                if (Server.MachineName == "TINY")
                {
                    Response.Redirect("/Basic/Index");
                }
                else
                {
                    Response.Write("Controller: Derived, Action: ProduceOutput");
                }
            }  

    ここでのActionメソッドProduceOutputは値を返さず、より多くの場合、View(「MyView」)のようなActionResultオブジェクトを返し、ViewはActionResultから継承されます.カスタムActionResultクラスを作成して使用することもできます.
    public class CustomRedirectResult : ActionResult { 
      public string Url { get; set; } 
      public override void ExecuteResult(ControllerContext context) { 
      string fullUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext); 
      context.HttpContext.Response.Redirect(fullUrl); 
      } 
    } 

    コントローラアクションメソッドでカスタムActionResultオブジェクトを返します.
    public ActionResultProduceOutput() { 
      if (Server.MachineName == "TINY") { 
          return new CustomRedirectResult { Url = "/Basic/Index" }; 
        } else { 
          Response.Write("Controller: Derived, Action: ProduceOutput"); 
          return null; 
        } 
    } 

    ここではリダイレクトを実現するActionResultオブジェクトを作成し、実際にMVCはこの機能を実現するためにRedirectResultを提供しています.
    ... 
    public ActionResult ProduceOutput() { 
    return new RedirectResult("/Basic/Index"); 
    } 
    ... 

    または、Controllerを呼び出すためのRedirect()メソッドをより便利にします.
    ... 
    public ActionResult ProduceOutput() { 
    return Redirect("/Basic/Index"); 
    } 
    ... 

    MVCは、RedirectResultに加えて、これらのActionResultを提供します.
  • ViewResult:ビューをレンダリングします.これは、コントローラから呼び出されたView()
  • と同じです.
  • PartialViewResult:一部のビューをレンダリングします.コントローラで呼び出されたPartialView()
  • と同じです.
  • RedirectToRouteResult:指定されたルーティング情報に基づいてHTTP 301または302リダイレクトコマンドを発行します.これは、コントローラがRedirectToAction、RedirectToActionPermanent、RedirectToRoute、RedirectToRoutePermanentを呼び出すのと同じです.
  • HttpUnauthorizedResult:HTTPステータスコード401を設定すると、許可されていません.
  • HttpNotFoundResult:HTTP 404-NOT FOUDエラーを返します.これはコントローラがHttpNotFound()を呼び出すのと同じです.
  • HttpStatusCodeResult:カスタムHTTPステータスコード
  • を返します.
  • EmptyResult:情報は返されません.

  • ビューに戻る
    最も多く使われているのは、コントローラActionメソッドでビューを返し、HTMLをレンダリングしてユーザーに返すことです.パラメータなしでView()を呼び出すこともできます.MVCは、Controlを含まないActionメソッドと同じ名前のViewを検索したり、パラメータにビューの名前を直接指定したりすることができます.
    public ViewResult Index() { 
      return View("Homepage"); 
    } 

    MVCはアプリケーションディレクトリの下でビューを検索し、領域Areaが有効である場合、検索パスは以下の通りである.
    •  /Areas/<AreaName>/Views/<ControllerName>/<ViewName>.aspx 
    •  /Areas/<AreaName>/Views/<ControllerName>/<ViewName>.ascx 
    •  /Areas/<AreaName>/Views/Shared/<ViewName>.aspx 
    •  /Areas/<AreaName>/Views/Shared/<ViewName>.ascx 
    •  /Areas/<AreaName>/Views/<ControllerName>/<ViewName>.cshtml 
    •  /Areas/<AreaName>/Views/<ControllerName>/<ViewName>.vbhtml 
    •  /Areas/<AreaName>/Views/Shared/<ViewName>.cshtml 
    •  /Areas/<AreaName>/Views/Shared/<ViewName>.vbhtml 

    Areaが使用されていない場合、検索パスは次のとおりです.
    •  /Views/<ControllerName>/<ViewName>.aspx 
    •  /Views/<ControllerName>/<ViewName>.ascx 
    •  /Views/Shared/<ViewName>.aspx 
    •  /Views/Shared/<ViewName>.ascx 
    •  /Views/<ControllerName>/<ViewName>.cshtml 
    •  /Views/<ControllerName>/<ViewName>.vbhtml 
    •  /Views/Shared/<ViewName>.cshtml 
    •  /Views/Shared/<ViewName>.vbhtml 

    MVCは、上記の順序でビューを検索すると、ファイルが1つ見つかった場合は検索を停止し、使用可能なビューファイルがない場合はリソースが見つからないエラーを返す.注意MVCはASPXビューエンジンの古いファイルを検索します.aspxと.ascx.
    Viewメソッドには、他にもいくつかのリロード呼び出し方法があります.
    return View("Index", "_AlternateLayoutPage"); //          
    return View("~/Views/Other/Index.cshtml"); //            ,   /  ~/  。

    コントローラからビューへのデータの転送
    ビューに渡すデータを呼び出しView()で直接指定できます.
    ... 
    public ViewResult Index() { 
    DateTime date = DateTime.Now; 
    return View(date); 
    } 
    ... 

    転送されたデータをビューで使用するには、次の手順に従います.
    @{ 
    ViewBag.Title = "Index"; 
    } 
    <h2>Index</h2> 
    The day is: @(((DateTime)Model).DayOfWeek) 

    強いタイプのビューでは、より便利に使用できます.
    @model DateTime 
    @{ 
    ViewBag.Title = "Index"; 
    } 
    <h2>Index</h2> 
    The day is: @Model.DayOfWeek

    動的キー値ペアのセットであるViewBagを使用して渡すこともできます.
    public ViewResult Index() { 
    ViewBag.Message = "Hello"; 
    ViewBag.Date = DateTime.Now; 
    return View(); 
    } 

    ビューで使用:
    @{ 
    ViewBag.Title = "Index"; 
    } 
    <h2>Index</h2> 
    The day is: @ViewBag.Date.DayOfWeek 
    <p /> 
    The message is: @ViewBag.Message 

    Viewbagはビューモデルよりも複数の値を渡すことができますが、VSはIntelliSenseプロンプトを与えず、ビューをレンダリングするときにエラーメッセージを与えるだけです.
    リダイレクト
    Redirectリダイレクトリクエストを使用することができます.
    public RedirectResult Redirect() { 
    return Redirect("/Example/Index"); 
    } 

    RedirectPermanentを使用して永続的にリダイレクトすることもできます.
    return RedirectPermanent("/Example/Index");

    Redirectテンポラリリダイレクト発行302 HTTPコードとは異なり、RedirectPermanentは301 HTTPコードを返送し、前者はブラウザが新しいURLを再GETすることを指示し、後者はブラウザがリダイレクト情報をキャッシュすることを指示し、以降は古いURLの要求に対して自動的に新しいURLに転向する.
    URLにリダイレクトする以外に、パスマッピング方法にリダイレクトできます.
    public RedirectToRouteResult Redirect() { 
      return RedirectToRoute(new { controller = "Example", action = "Index", ID = "MyID" }); 
    } 

    またはアクションメソッド:
    public RedirectToRouteResult RedirectToRoute() { 
        return RedirectToAction("Index"); 
    } 

    コントローラのアクションメソッドを指定できます.
    public RedirectToRouteResult Redirect() { 
        return RedirectToAction("Index", "Basic"); 
    }  

    別のコントローラのActionにリダイレクトしたときにデータを渡したい場合はどうすればいいですか?TempDataを使用できます.
    public RedirectToRouteResult RedirectToRoute() { 
    TempData["Message"] = "Hello"; 
    TempData["Date"] = DateTime.Now; 
    return RedirectToAction("Index"); 
    } 

    新しいビューでTempDataを読み込みます.
    @{ 
    ViewBag.Title = "Index"; 
    } 
    <h2>Index</h2> 
    The day is: @(((DateTime)TempData["Date"]).DayOfWeek) 
    <p /> 
    The message is: @TempData["Message"]

    ViewBagはコントローラと同名ビューのみで使用されるのとは異なり、TempDataはセッションセッションセッションセッションデータに類似しており、異なるコントローラ/ビューで共有可能であるが、セッションセッション間要求とは異なり、TempDataのデータTempDataが読み込まれると削除される.TempData.Peekはデータを読み込みますが、データは削除しません.
    DateTime time = (DateTime)TempData.Peek("Date"); 

    TempData.Keepはタグデータを削除しないことができますが、再読み込みされると再びタグ削除されます.参照カウンタと似ています.
    TempData.Keep("Date"); 

    HTTPステータスコードを返す
    404エラーなどのHTTPステータスコードを返すことができます.
    public HttpStatusCodeResult StatusCode() { 
    return new HttpStatusCodeResult(404, "URL cannot be serviced"); 
    } 

    またはダイレクトコール:
    return HttpNotFound(); 

    401認証されていないエラー:
    return new HttpUnauthorizedResult();

     
    以上は『Apress Pro ASP.NET MVC 4』第4版の関連内容のまとめであり、不詳な点は原版http://www.apress.com/9781430242369を参照.