在不同的控制器和视图之间传递数据

问题描述

在asp.net core 3.1中,我有两个名为 Home Index 的控制器,两个名称相同的视图。

我想在家庭控制器索引视图之间传递数据。我尝试使用 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();
    });
}
,

这里有两个主要选项:

  1. Session and state management 如果您只需要会话中的数据并且不使用大量数据对象,则可以采用这种方法。请记住,为了使用会话状态,您需要先配置它。 Session Configuration
  2. Repository Pattern 这需要更多的设置,但将允许您在抽象数据层的会话外部维护数据
,

您确实应该传递模型,而不是使用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>

在此示例中,当应用程序启动时-索引页面将与传递的模型一起显示

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...