Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In dotnet mvc 5, how to inject a service into a view?

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.

like image 220
HongyanShen Avatar asked Dec 08 '16 02:12

HongyanShen


People also ask

Which keyword is used to inject services in the view?

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.

What is MVC view injection?

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.

How do you pass model data into a view?

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.


1 Answers

ASP.NET MVC 5 doesn't have @inject

This keyword only exists in ASP.NET Core.

Work-around using @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.

like image 78
Fab Avatar answered Nov 15 '22 03:11

Fab