【问题标题】:passing Data Between Different Controllers and Views在不同的控制器和视图之间传递数据
【发布时间】:2021-09-02 14:17:12
【问题描述】:

在 ASP.NET-Core 3.1 中,我有两个名为 HomeIndex 的控制器和两个名称相同的视图。

我想在主控制器和索引视图之间传递数据**。我尝试使用ViewBagViewData,但我无法解决问题。

【问题讨论】:

  • 你能分享你试过的代码吗?

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

这里有两个主要选项:

  1. Session and state management 如果您只需要会话中的数据并且不使用大量数据对象,那么这是要走的路。请记住,为了使用会话状态,您需要先对其进行配置。
  2. Repository Pattern 这需要更多设置,但允许您在抽象数据层中维护会话之外的数据

【讨论】:

    【解决方案2】:

    你可以试试:

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

    【讨论】:

    • 非常感谢,但是当我尝试使用这种方式时,我遇到了错误 :: An object reference is required for the non-static field, method, or property 'System.Web.Mvc .Controller.HttpContext.get'
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多