Home > Back-end >  How can i pass ViewData to Action method from class?
How can i pass ViewData to Action method from class?

Time:09-21

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related