[英]passing Data Between Different Controllers and Views
我有兩個名為Home和Index 的控制器和兩個在 asp.net core 3.1 中命名相同的視圖。
我想在Home Controller到Index View之間傳遞數據。 我嘗試使用ViewBag和ViewData,但無法解決問題。
你可以試試:
HttpContext.Session.SetString(SessionKeyName, "The Value You Want To Store");
參考: https : //docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1
您還需要先設置會話:
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddControllersWithViews();
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
});
}
你真的應該傳遞一個模型而不是使用 viewbag 或 viewdata。
定義一個模型,如下所示:
public class ViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
在您的 HomeController 中創建一個 IActionResult,如下所示:
public IActionResult Home()
{
ViewModel viewmodel = new ViewModel
{
FirstName = "Alex",
LastName = "Leo"
};
return View("/Views/Index/Index.cshtml",viewmodel);
}
您的 Index.cshtml 將采用傳遞的模型,它將被定義如下:
@model ViewModel
@{
ViewData["Title"] = "Index Page";
}
<label>@Model.FirstName</label>
<label>@Model.LastName</label>
在這個例子中,當應用程序啟動時 - 索引頁面將與傳遞的模型一起顯示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.