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.
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.
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
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>