1.2.3.Pass data to views

  • 有三種方式

    • 1.最基本的方式

      • 1.修改controller: MoviesController.cs

        // GET: Movies/Random
        public ActionResult Random()
        {
            var movie = new Movie() { Name = "Shrek" };
            return View(movie);
        }
      • 2.修改view: Random.cshtml

        @model Vidly2.Models.Movie
        @{
         ViewBag.Title = "Random";
         Layout = "~/Views/Shared/_Layout.cshtml";
        }
        h2@model.Name/h2
    • 2.ViewData

      • 1.修改controller: MoviesController.cs

        // GET: Movies/Random
        public ActionResult Random()
        {
            var movie = new Movie() { Name = "Shrek" };
            ViewBag.Movie = movie;
        
            return View();
        }
      • 2.修改view: Random.cshtml

        @using Vidly2.Models
        @model Vidly2.Models.Movie
        @{
         ViewBag.Title = "Random";
         Layout = "~/Views/Shared/_Layout.cshtml";
        }
        h2@(((Movie)ViewData["Movie"]).Name)/h2
    • 3.ViewBag

      • 1.修改controller: MoviesController.cs

        // GET: Movies/Random
        public ActionResult Random()
        {
          var movie = new Movie() { Name = "Shrek" };
          ViewData["Movie"] = movie;
          return View();
        }
      • 2.修改view: Random.cshtml

        @using Vidly2.Models
        @model Vidly2.Models.Movie
        @{
         ViewBag.Title = "Random";
         Layout = "~/Views/Shared/_Layout.cshtml";
        }
        h2@ViewBag.Movie/h2

Last updated