Asp.net vNext 學習之路(二)


   View component(視圖組件)應該是MVC6 新加的一個東西,類似於分部視圖。本文將演示在mvc 6中 怎么添加視圖組件以及怎么在視圖中注入一個服務。

 本文包括以下內容:

1,創建一個新的asp.net vNext 項目。

2,安裝 KVM(K version manager)。

3,如何運行EF 數據庫遷移。

4,什么是 view component。

5,如何在 mvc 6 中添加一個view component 。

6,如何在view 中注入一個服務。

一 創建一個新的asp.net vNext 項目

 打開vs 2015 。 File>New >Project>Templates>C#>Web>Asp.Net Application 點擊OK。然后選擇 New ASP.NET Project :

 

由於是演示我就在Home的文件下新建一個視圖Test.cshtml 相應的HomeController 添加如下代碼:

1    public IActionResult Test()
2    {
3        return View();
5     }

在Models 文件夾里新建一個TestModel類:

1    public class TestModel
2     {
3         public int ID { get; set; }
4 
5         public string Title { get; set; }
6     }

然后在 Models\IdentityModels.cs 文件的 ApplicationDbContext類中添加一句代碼:

 1 public DbSet<TestModel> TestItems { get; set; } 

表示我們加了一張表在數據庫中。但是現在運行肯定會報錯,我們需要安裝KVM。

二 安裝 KVM(K version manager)

 首先在管理員權限下運行cmd。然后把下面這句代碼拷進去。

 1 @powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1'))" 

 如果成功的話說明KVM安裝成功了。

然后重新打開一個cmd 。輸入 KVM upgrade  成功之后我們就可以做EF的遷移了。

 三 如何運行EF 數據庫遷移

 首先打開cmd 然后我們需要進入項目的當前目錄:接下來運行  k ef migration add initial  k ef migration applay

 

ok 這樣 ef 就遷移好了,我們會發現項目中多了一些東西

 

然后我們需要在Startup.cs 中的 Configure 方法中 添加如下代碼:

1     app.UseServices(service =>
2             {
3                 service.AddEntityFramework()
4                           .AddSqlServer()
5                           .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
6                               Configuration.Get("Data:DefaultConnection:ConnectionString")));
7             });

在HomeController 中部分代碼:

 1    ApplicationDbContext context = new ApplicationDbContext();
 2 
 3         public IActionResult Index()
 4         {
 5             return View();
 6         }
 7 
 8         public IActionResult Test()
 9         {
10             context.Add(new TestModel() { Title = "test1" });
11 
12 
13             context.SaveChanges();
14 
15             List<TestModel> list = context.Set<TestModel>().ToList();
16 
17             return View(list);
18         }
19 
20         protected override void Dispose(bool disposing)
21         {
22             base.Dispose(disposing);
23 
24             context.Dispose();
25         }

Test.cshtml 文件代碼:

 1 @model List<WebApplication3.Models.TestModel>
 2 
 3 @{
 4     ViewBag.Title = "Test";
 5 
 6 }
 7 <table class="table  table-hover table-bordered  table-condensed">
 8     <thead>
 9         <tr>
10             <th>ID</th>
11             <th>Title</th>
12         </tr>
13     </thead>
14     <tbody>
15         @foreach (var item in Model)
16         {
17         <tr>
18             <td>@item.ID</td>
19             <td>@item.Title</td>
20         </tr>
21         }
22 
23     </tbody>
24 </table>

Ok 運行一下項目效果如下:

四 什么是 view component

    作為Mvc6 新添加的東西和之前的partial view 還是比較類似的。但是要比partial view 更加的靈活和強大。和controller 和 view的關系一樣是關注點分離的, component 相當於是一個mini的controller 

它是去響應局部的模塊而非是完整的。我們可以用view component 來解決更加復雜的頁面上的問題。它有兩部分組成 一個后台類和前台的Razor view (可以回掉后台類的方法)。 

五 如何在 mvc 6 中添加一個view component 

  首先我在項目中新建一個ViewComponents的文件夾(這個文件夾名字可以隨意命名),然后文件夾里新建一個 TestViewComponent 類 :

 1  public class TestViewComponent : ViewComponent
 2     {
 3         ApplicationDbContext context;
 4 
 5 
 6         public TestViewComponent(ApplicationDbContext context)
 7         {
 8             this.context = context;
 9         }
10 
11         public IViewComponentResult Invoke(int max)
12         {
13             var item = context.Set<TestModel>().Where(p => p.ID > max).ToList();
14 
15             return View(item);
16         }
17 
18     }

然后我們需要添加一個 component  view 。在 Home文件夾新建Components(必須這樣命名)文件夾然后 里面新建一個文件夾 Test(這個名字是和之前的那個TestComponent 相匹配的)

Test 文件夾里新建 一個視圖,隨意命名 default.cshtml  

 1 @model List<WebApplication3.Models.TestModel>
 2 @{
 3     // ViewBag.Title = "Home Page";
 4 }
 5 
 6 <h3>Priority Items</h3>
 7 <ul>
 8     @foreach (var item in Model)
 9     {
10         <li>@item.ID ----- @item.Title</li>
11     }
12 </ul>

 那么我們就可以去調這個view component了 在Test.cshtml

 1 @model List<WebApplication3.Models.TestModel>
 2 
 3 @{
 4     ViewBag.Title = "Test";
 5 
 6 }
 7 <table class="table  table-hover table-bordered  table-condensed">
 8     <thead>
 9         <tr>
10             <th>ID</th>
11             <th>Title</th>
12         </tr>
13     </thead>
14     <tbody>
15         @foreach (var item in Model)
16         {
17         <tr>
18             <td>@item.ID</td>
19             <td>@item.Title</td>
20         </tr>
21         }
22 
23     </tbody>
24 </table>
25 
26 <div class="row">
27     @Component.Invoke("Test", 2);
28 </div>

Ok  看一下效果 :

 

那個view components 的意思是所有ID>2的列表。

六 如何在view 中注入一個服務 
 首先新建一個StaticService 類

 

 1  public class StatisticsService
 2     {
 3         private ApplicationDbContext db;
 4 
 5         public StatisticsService(ApplicationDbContext db)
 6         {
 7             this.db = db;
 8         }
 9 
10 
11         public int GetCount()
12         {
13             return db.TestItems.Count();
14         }
15 
16     }

然后Test.cshtml 代碼:

 1 @model List<WebApplication3.Models.TestModel>
 2 @inject WebApplication3.Models.StatisticsService service
 3 <table class="table  table-hover table-bordered  table-condensed">
 4     <thead>
 5         <tr>
 6             <th>ID</th>
 7             <th>Title</th>
 8         </tr>
 9     </thead>
10     <tbody>
11         @foreach (var item in Model)
12         {
13         <tr>
14             <td>@item.ID</td>
15             <td>@item.Title</td>
16         </tr>
17         }
18 
19     </tbody>
20 </table>
21 
22 <div class="row">
23     @Component.Invoke("Test", 2);
24 </div>
25 
26 <h1>
27    Total: @service.GetCount()  
28 </h1>

在 startup.cs 中注冊該類:

 1     public void ConfigureServices(IServiceCollection services)
 2         {
 3             // Add EF services to the services container.
 4             services.AddEntityFramework(Configuration)
 5                 .AddSqlServer()
 6                 .AddDbContext<ApplicationDbContext>();
 7 
 8             // Add Identity services to the services container.
 9             services.AddDefaultIdentity<ApplicationDbContext, ApplicationUser, IdentityRole>(Configuration);
10 
11             // Add MVC services to the services container.
12             services.AddMvc();
13 
14             services.AddTransient<StatisticsService>();
15             // Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
16             // You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
17             // services.AddWebApiConventions();
18 
19         }

運行 看效果:

 

 

七 總結

 Mvc 6 還是加了不少的東西的,不過只會讓以后的開發會原來越簡單。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM