簡體   English   中英

在不同的控制器和視圖之間傳遞數據

[英]passing Data Between Different Controllers and Views

我有兩個名為HomeIndex 的控制器和兩個在 asp.net core 3.1 中命名相同的視圖。

我想在Home ControllerIndex View之間傳遞數據。 我嘗試使用ViewBagViewData,但無法解決問題。

你可以試試:

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();
    });
}

這里有兩個主要選項:

  1. 會話和狀態管理如果您只需要會話中的數據並且不處理大量數據對象,那么這就是您要走的路。 請記住,為了使用會話狀態,您需要先配置它。 會話配置
  2. 存儲庫模式這需要更多的設置,但允許您在抽象數據層中維護會話之外的數據

你真的應該傳遞一個模型而不是使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM