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();
  4. }

在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类中添加一句代码:

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

表示我们加了一张表在数据库中。但是现在运行肯定会报错,我们需要安装KVM。

二 安装 KVM(K version manager)

首先在管理员权限下运行cmd。然后把下面这句代码拷进去。

@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. context.SaveChanges();
  13.  
  14. List<TestModel> list = context.Set<TestModel>().ToList();
  15.  
  16. return View(list);
  17. }
  18.  
  19. protected override void Dispose(bool disposing)
  20. {
  21. base.Dispose(disposing);
  22.  
  23. context.Dispose();
  24. }

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. public TestViewComponent(ApplicationDbContext context)
  6. {
  7. this.context = context;
  8. }
  9.  
  10. public IViewComponentResult Invoke(int max)
  11. {
  12. var item = context.Set<TestModel>().Where(p => p.ID > max).ToList();
  13.  
  14. return View(item);
  15. }
  16.  
  17. }

然后我们需要添加一个 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", );
  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. public int GetCount()
  11. {
  12. return db.TestItems.Count();
  13. }
  14.  
  15. }

然后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 还是加了不少的东西的,不过只会让以后的开发会原来越简单。

Asp.net vNext 学习之路(二)的更多相关文章

  1. Asp.net vNext 学习之路(三)

    asp.net vNext 对于构建asp.net 程序带来了一些重大的改变,让我们开发asp.net 程序的时候更加的方便和高效. 1,可以很容易的去管理客户端的包比如jquery,bootstra ...

  2. Asp.net vNext 学习之路(一)

    概述 asp.net vNext 也叫 asp.net 5.0,意思是微软推出的下一个版本的asp.net.可以说是微软对asp.net的一个比较重大的重新设计, asp.net vNext是一 个比 ...

  3. Asp.net vNext 学习3

    Asp.net vNext 学习之路(三) asp.net vNext 对于构建asp.net 程序带来了一些重大的改变,让我们开发asp.net 程序的时候更加的方便和高效. 1,可以很容易的去管理 ...

  4. Asp.net vNext 学习1

    Asp.net vNext 学习之路(一) 概述 asp.net vNext 也叫 asp.net 5.0,意思是微软推出的下一个版本的asp.net.可以说是微软对asp.net的一个比较重大的重新 ...

  5. Redis——学习之路二(初识redis服务器命令)

    上一章我们已经知道了如果启动redis服务器,现在我们来学习一下,以及如何用客户端连接服务器.接下来我们来学习一下查看操作服务器的命令. 服务器命令: 1.info——当前redis服务器信息   s ...

  6. [整理]ASP.NET vNext学习资源

    http://www.hanselman.com/blog/IntroducingASPNETVNext.aspx http://blogs.msdn.com/b/dotnet/archive/201 ...

  7. zigbee学习之路(二)点亮LED

    一.前言 今天,我来教大家如何点亮led,这也是学习开发板最基础的步骤了. 二.原理分析 cc2530芯片跟虽然是51的内核,但是它跟51单片机还是有区别的,51单片机不需要对IO口进行配置,而cc2 ...

  8. ASP.NET MVC 学习之路-4

    本文在于巩固基础 模型绑定 从URL 获取值 public ActionResult About(int id) { ViewBag.Id = id; return View(); } @{ View ...

  9. ASP.NET MVC 学习之路-1

    本文在于巩固基础 学习参考书籍:ASP.NET MVC4 Web编程 首先确定我们学习MVC的目标: 我们学习ASP.NET MVC的目的在于开发健壮的.可维护的Web应用,当然这需要一定的知识基础, ...

随机推荐

  1. css美化Div边框的样式实例

    很多时候如果不是用了很多样式,很难把边框修饰得好看,看了一篇博文,觉得真的挺漂亮,也挺好看. 转载的博文地址 将这段美化的css代码 border:1px solid #96c2f1;backgrou ...

  2. Codeforces 480.E Parking Lot

    E. Parking Lot time limit per test 3 seconds memory limit per test 256 megabytes input standard inpu ...

  3. Codeforces 578.C Weakness and Poorness

    C. Weakness and Poorness time limit per test 2 seconds memory limit per test 256 megabytes input sta ...

  4. Tensorboard教程:监控指标可视化

    Tensorflow监控指标可视化 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 强烈推荐Tensorflow实战Google深度学习框架 实验平台: Tensorflow1.4. ...

  5. Unix处理目标文件的工具

  6. CSS盒子知识

    此随笔写于学习完CSS盒子之后,所遇到的问题和感悟记录. 1.IE盒子: IE盒子的特性:对于IE浏览器来说width不是内容宽度.而是内容+外边距+边框的内容总和. 也就是说当盒子增加10px;那么 ...

  7. HDU 5213 分块 容斥

    给出n个数,给出m个询问,询问 区间[l,r] [u,v],在两个区间内分别取一个数,两个的和为k的对数数量. $k<=2*N$,$n <= 30000$ 发现可以容斥简化一个询问.一个询 ...

  8. IP判断 (字符串处理)

    关于IP合法性判断的题目,每个oj上的约束条件不尽相同,我就根据自己做过的题目吧所有的约束条件汇总到一块,到时候做题时只需要把多余的越是条件删掉即可 题目描述: 对于IP我们总会有一定的规定,合法的I ...

  9. Redis数据类型之列表(list)

    1. 什么是列表 redis的列表使用双向链表实现,往列表中放元素的时候复杂度是O(1),但是随机访问的时候速度就不行了,因为需要先遍历到指定的位置才可以取到元素. 既然列表是使用链表实现的,那么就说 ...

  10. 配置node,sass,淘宝镜像环境

    由于最近由于刚到手一台新的thinkpad(哈哈,宝宝是个小穷B,木有小苹果),所以工作开发中所用到的环境就需要重新安装一下啦,这里的话,我就把我目前所用到的进行总结一下,其余的会在以后的开发过程中, ...