从控制器传值到视图的几种方式:
其中HttpContext.Session需要在Program.cs文件中注册使用。
ViewBag.UserA = "张三"; //使用:@ViewBag.User
ViewData["UserB"] = "李四"; //使用:@ViewData["UserB"]
TempData["UserC"] = "王五"; //使用:@TempData["UserC"]
HttpContext.Session.SetString("UserD", "赵六"); //使用:@Context.Session.GetString("UserD")
object UserE = "田七"; //使用:@Model
Program.cs文件:需要注册使用Session中间件,否则报错:
//表示整个应用程序,调用CreateBuilder方法创建一个WebApplicationBuilder对象
//初始化当前应用程序的管道容器
var builder = WebApplication.CreateBuilder(args);
//向管道容器添加注册中间件
//添加注册控制器视图中间件
builder.Services.AddControllersWithViews();
//添加注册Session中间件
builder.Services.AddSession();
//配置管道容器中间件,构造WebApplication实例
var app = builder.Build();
//判断是否是开发模式
if (!app.Environment.IsDevelopment())
{
//向管道中添加中间件,该中间件将捕获异常、记录异常、重置请求路径并重新执行请求
app.UseExceptionHandler("/Shared/Error");
//向管道中添加用于使用HSTS的中间件,该中间件添加了Strict Transport Security标头。默认值为30天
app.UseHsts();
}
//向管道添加Session中间件
app.UseSession();
//向管道添加用于将HTTP请求重定向到HTTPS的中间件
app.UseHttpsRedirection();
//向管道添加为当前请求路径启用静态文件服务
app.UseStaticFiles();
//向管道添加路由配置中间件
app.UseRouting();
//向管道添加鉴权中间件
app.UseAuthentication();
//向管道添加授权中间件
app.UseAuthorization();
//向管道添加默认路由中间件
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
//向管道添加启动应用程序中间件
app.Run();
控制器代码:
/// <summary>
/// Get请求
/// Home控制器的Index
/// </summary>
/// <returns>Index视图</returns>
[HttpGet]
public IActionResult Index()
{
ViewBag.UserA = "张三";
ViewData["UserB"] = "李四";
TempData["UserC"] = "王五";
HttpContext.Session.SetString("UserD", "赵六");
object UserE = "田七";
return View(UserE);
}
视图代码:
@{
ViewBag.Title = "首页";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@model string;
<h1>当前是Home/Index页</h1>
<table>
<thead>
<tr>
<td>名称</td>
<td>数据</td>
</tr>
</thead>
<tbody>
<tr>
<td>UserA</td>
<td>@ViewBag.UserA</td>
</tr>
<tr>
<td>UserB</td>
<td>@ViewData["UserB"]</td>
</tr>
<tr>
<td>UserC</td>
<td>@TempData["UserC"]</td>
</tr>
<tr>
<td>UserD</td>
<td>@Context.Session.GetString("UserD")</td>
</tr>
<tr>
<td>UserE</td>
<td>@Model</td>
</tr>
</tbody>
</table>