How to view ViewData data between ViewComponent in Asp.net core

I have two ViewComponent and I want to use ViewData or another technique to exchange some data between them, and then use this data in the main view, but it is not, and the ViewData for the ViewComponent is null when it is rich, if the condition for ViewComponent.

public class OneViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(Page page, Zone zone)
    {
        //some operation

        string text = "one";

        if(ViewData["data"] != null)
        {
            ViewData["data"] = ViewData["data"].ToString() + text;
        }
        else
        {
            ViewData["data"] = text;
        }

        return View();
    }
}

public class TwoViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(Page page, Zone zone)
    {
        //some operation

        string text = "two";

        if(ViewData["data"] != null)
        {
            ViewData["data"] = ViewData["data"].ToString() + text;
        }
        else
        {
            ViewData["data"] = text;
        }

        return View();
    }
}
+6
source share
2 answers

ViewDatasimilar to ViewBag. You use it only if you want to transfer data from the controller to the view. For this, I always prefer the View Model.

To transfer data through a component, you have the following two options:

TempData ViewData:

Install-Package Microsoft.AspNetCore.Mvc.ViewFeatures

Startup

services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();

ConfigureServices. CookieTempDataProvider ITempDataProvider SessionStateTempDataProvider.

TempData :

this.TempData["data"] = "my value";

TempData :

var data = this.TempData["data"];

:

@this.TempData["data"]

HttpContext.Items: . HttpContext.Items :

this.HttpContext.Items["data"] = "my value"; 

, , :

var data = this.HttpContext.Items["data"];

, :

@this.Context.Items["data"]

TempData HttpContext.Items: HttpContext.Items TempData:

  • HttpContext.Items , .
  • TempData . , TempData.Keep()
  • , TempData ITempDataDictionary ITempDataDictionary.
+9

Imho - , ViewComponent . .

, , , .. .

@Html.Partial("PartialName", customViewData)

"one" "two" @Html.Partial("PartialName", "one"), @Html.Partial("PartialName", "two")

ViewComponents view, controler +. +, ViewComponent .

ViewComponents .

, , , .

3 : , ( ) , . , viewmodel ( ViewData, ), , .

+4

Source: https://habr.com/ru/post/1676585/


All Articles