In dotnet core mvc,i can inject a service into a view by using @inject directive,but how to do this in dotnet mvc 5.It seems that there is no @inject directive in mvc 5.
A service can be injected into a view using the @inject directive. You can think of @inject as adding a property to the view, and populating the property using DI.
View injection can be useful for populating UI elements, like selection list, radio buttons etc. This will increase code re-usability and keep your Controller clean by minimizing the amount of code required on Controllers. Reference. http://aspnetmvc.readthedocs.io/projects/mvc/en/latest/views/dependency-injection.html.
The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.
@inject
This keyword only exists in ASP.NET Core.
@model
However you can still inject a dependency in the controller and from the controller pass it to the model. @model
and @Model
can be used freely in the razor page/view.
MyController.cs:
public class MyController : Controller
{
public MyController(IMyDependency dependency)
{
_dependency = dependency;
}
public ActionResult Index()
{
View(new ViewModel
{
Dependency = _dependency
});
}
}
Razor.cshtml:
@model ViewModel
@if (Model.Dependency.CanView)
{
<!-- Put the code here -->
}
It also means you can put a IServiceProvider
in the model and resolve directly in the view. However, in terms of separation of concerns, it's not the ideal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With