.NET MVC 页面传值方式
控制器
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using mvcProject.Models; namespace mvcProject.Controllers { public class FirstController : Controller { private readonly ILogger<FirstController> _logger; public FirstController(ILogger<FirstController> logger) { _logger = logger; } public IActionResult Index() { this._logger.LogWarning("First页面加载了"); #region ViewData base.ViewData["User"] = (new CurrentUser() { Id = 1, Name = "杜浩然", Age = 23, Email = "1931209209@qq.com", Password = "123456", LoginTime = DateTime.Now }); #endregion #region ViewBag base.ViewBag.User = (new CurrentUser() { Id = 1, Name = "杜浩然", Age = 23, Email = "1931209209@qq.com", Password = "123456", LoginTime = DateTime.Now }); #endregion #region TempData base.TempData["User"] = (new CurrentUser() { Id = 1, Name = "杜浩然", Age = 23, Email = "1931209209@qq.com", Password = "123456", LoginTime = DateTime.Now }); #endregion #region Session if (string.IsNullOrWhiteSpace(this.HttpContext.Session.GetString("CurrentUserSession"))) { base.HttpContext.Session.SetString("CurrentUserSession", Newtonsoft.Json.JsonConvert.SerializeObject(new CurrentUser() { Id = 1, Name = "杜浩然", Age = 23, Email = "1931209209@qq.com", Password = "123456", LoginTime = DateTime.Now })); } #endregion #region Model return View(new CurrentUser { Id = 1, Name = "杜浩然", Age = 23, Email = "1931209209@qq.com", Password = "123456", LoginTime = DateTime.Now }); #endregion } } }
视图
@model mvcProject.Models.CurrentUser @using Microsoft.AspNetCore.Http @{ Layout = null; CurrentUser userViewData = ViewData["User"] as CurrentUser; CurrentUser userViewBag = ViewBag.User as CurrentUser; CurrentUser userTempData = TempData["User"] as CurrentUser; CurrentUser userSession = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentUser>(base.Context.Session.GetString("CurrentUserSession")); } <h5>ViewData:@(((CurrentUser)ViewData["User"]).Name)</h5> <h5>userViewData:@userViewData.Name</h5> <h5>ViewBag:@(((CurrentUser)ViewBag.User).Age)</h5> <h5>userViewBag:@userViewBag.Age</h5> <h5>TempData:@(((CurrentUser)TempData["User"]).Email)</h5> <h5>userTempData:@userTempData.Email</h5> <h5>Model:@base.Model.Password</h5> <h5>userSession:@userSession.LoginTime</h5> <p>我是一个测试段落</p>