发布:2022/7/4 23:38:00作者:管理员 来源:本站 浏览次数:1207
MVC从控制器传值到视图一共有五种方式
ViewBag
ViewData
TempData
Session
Model
1,用VS2022新建一个基于.net6的MVC项目
2,添加一个控制器FirstController如下
public class FirstController : Controller
{
public IActionResult Index()
{
ViewBag.User1 = "张三";
ViewData["User2"]="李四";
TempData["User3"]="王五";
HttpContext.Session.SetString("User4", "赵六");
object User5 = "田七";
return View(User5);
}
}
3,添加对应的视图内容如下
<h1>This is First Index</h1>
<h2>User1=@ViewBag.User1</h2>
<h2>User1=@ViewData["User2"]</h2>
<h2>User2=@TempData["User3"]</h2>
<h2>User4=@Context.Session.GetString("User4")</h2>
<h2>User5=@Model</h2>
这个时候运行会报错,还要在Program.cs引入Session
需要在Program.cs添加如下两句
builder.Services.AddSession();
...
app.UseSession();
PS: Net6的项目没有了Setup.cs这个文件了, 并且Program.cs也是用新的语法写的
最终Program.cs代码如下
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSession(); //添加Session
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseSession();//启用Session
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
运行项目, 打开http://localhost:5224/first/index就可以看到页码上显示的值了
类似这样:
This is First Index
User1=张三
User1=李四
User2=王五
User4=赵六
User5=田七
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4