#asp.net core mvc 的视图注入

View injection is the most useful feature introduced in ASP.NET Core.

1.添加一个FruitsService


public class FruitServices  
{  
    public List<string> GetFruits()  
    {  
        return new List<string>() { "Mango", "Apple", "Apricot", "Banana", "Grapes" };  
    }  
}  

2.Inject in View

基本语法:


@inject <service> <name>

@inject 为DI的指令

待注入服务的名称

服务的名字,代表一个服务的实例。

---FruitsInjection.cshtml---


@inject WebAppWithIndividualUserAccounts.Services.FruitServices fruitService

<h3>Fruit List</h3>

<ul>

 @foreach (var name in fruitService.GetFruits())

 {

     <li>@name</li>

 }

</ul>

3.配置IOC

---Startup.cs---中


public void ConfigureServices(IServiceCollection services)

{

// Add framework services.

 services.AddMvc();

 services.AddTransient<FruitServices>();

}

ref:http://www.c-sharpcorner.com/article/view-injection-in-asp-net-core-mvc/

posted @ 2016-08-10 09:48 _DN 阅读(...) 评论(...) 编辑 收藏