Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

274
Visualizações
How can i pass ViewData to Action method from class?

I want to replace

public IActionResult Index()
{
ViewData["SomeData"] = ...
return View();
}

with

public IActionResult Index()
{
 _someDataCretor.Create(...);
return View();
}

What should happen in SomeDataCretor.Create() for this to work? For View to get ViewData.

Thanks.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The ViewData is defined as public ViewDataDictionary ViewData { get; set; }. Therefore you can pass it as a parameter to your method:

public IActionResult Index()
{
    _someDataCretor.Create(ViewData);
    return View();
}

And in the Create(ViewDataDictionary viewdata) method:

viewdata["SomeData"] = ...;

But I suppose a more reasonable approach is to return an object from the Create() method that will be passed to the Index view as a view model.

over 4 years ago · Santiago Trujillo Relatório

0

Assuming _someDataCreator contains the data you want in the view, you would just pass it as the model:

return View(_someDataCreator);

or if it returns an object you can return that result:

var result = _someDateCreator.Create(...);
return View(result);

and in your view reference that type:

@model My.Namespace.MyObject
over 4 years ago · Santiago Trujillo Relatório

0

ViewData is used to pass data from controllers to views and within views, including partial views and layouts.You can try to use TempData,here is a demo:

public class MyDepedency
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;

        public MyDepedency(IHttpContextAccessor httpContextAccessor, ITempDataDictionaryFactory tempDataDictionaryFactory)
        {
            _httpContextAccessor = httpContextAccessor;
            _tempDataDictionaryFactory = tempDataDictionaryFactory;
        }

        public void Create()
        {
            var httpContext = _httpContextAccessor.HttpContext;
            var tempData = _tempDataDictionaryFactory.GetTempData(httpContext);

            // use tempData as usual
            tempData["SomeData"] = "Bar";
        }
     
    }

Startup:

public void ConfigureServices(IServiceCollection services)
        {
            ...
            services.AddControllersWithViews();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton<MyDepedency, MyDepedency>();
        }

Controller:

public class HomeController : Controller
    {
        public MyDepedency _myDepedency;
       
        public HomeController(MyDepedency myDepedency)
        {
            _myDepedency = myDepedency;
        }

        public IActionResult Index()
        {
            _myDepedency.Create();
            return View();
            
        }

View:

<h1>@TempData.Peek("SomeData")</h1>

result: enter image description here

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda