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 添加如下代码:

    public IActionResult Test()
{
return View();
}

在Models 文件夹里新建一个TestModel类:

    public class TestModel
{
public int ID { get; set; } public string Title { get; set; }
}

然后在 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 方法中 添加如下代码:

     app.UseServices(service =>
{
service.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
Configuration.Get("Data:DefaultConnection:ConnectionString")));
});

在HomeController 中部分代码:

    ApplicationDbContext context = new ApplicationDbContext();

         public IActionResult Index()
{
return View();
} public IActionResult Test()
{
context.Add(new TestModel() { Title = "test1" }); context.SaveChanges(); List<TestModel> list = context.Set<TestModel>().ToList(); return View(list);
} protected override void Dispose(bool disposing)
{
base.Dispose(disposing); context.Dispose();
}

Test.cshtml 文件代码:

 @model List<WebApplication3.Models.TestModel>

 @{
ViewBag.Title = "Test"; }
<table class="table table-hover table-bordered table-condensed">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.ID</td>
<td>@item.Title</td>
</tr>
} </tbody>
</table>

Ok 运行一下项目效果如下:

四 什么是 view component

作为Mvc6 新添加的东西和之前的partial view 还是比较类似的。但是要比partial view 更加的灵活和强大。和controller 和 view的关系一样是关注点分离的, component 相当于是一个mini的controller

它是去响应局部的模块而非是完整的。我们可以用view component 来解决更加复杂的页面上的问题。它有两部分组成 一个后台类和前台的Razor view (可以回掉后台类的方法)。

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

首先我在项目中新建一个ViewComponents的文件夹(这个文件夹名字可以随意命名),然后文件夹里新建一个 TestViewComponent 类 :

  public class TestViewComponent : ViewComponent
{
ApplicationDbContext context; public TestViewComponent(ApplicationDbContext context)
{
this.context = context;
} public IViewComponentResult Invoke(int max)
{
var item = context.Set<TestModel>().Where(p => p.ID > max).ToList(); return View(item);
} }

然后我们需要添加一个 component  view 。在 Home文件夹新建Components(必须这样命名)文件夹然后 里面新建一个文件夹 Test(这个名字是和之前的那个TestComponent 相匹配的)

Test 文件夹里新建 一个视图,随意命名 default.cshtml

 @model List<WebApplication3.Models.TestModel>
@{
// ViewBag.Title = "Home Page";
} <h3>Priority Items</h3>
<ul>
@foreach (var item in Model)
{
<li>@item.ID ----- @item.Title</li>
}
</ul>

那么我们就可以去调这个view component了 在Test.cshtml

 @model List<WebApplication3.Models.TestModel>

 @{
ViewBag.Title = "Test"; }
<table class="table table-hover table-bordered table-condensed">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.ID</td>
<td>@item.Title</td>
</tr>
} </tbody>
</table> <div class="row">
@Component.Invoke("Test", );
</div>

Ok  看一下效果 :

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

六 如何在view 中注入一个服务 
 首先新建一个StaticService 类

  public class StatisticsService
{
private ApplicationDbContext db; public StatisticsService(ApplicationDbContext db)
{
this.db = db;
} public int GetCount()
{
return db.TestItems.Count();
} }

然后Test.cshtml 代码:

 @model List<WebApplication3.Models.TestModel>
@inject WebApplication3.Models.StatisticsService service
<table class="table table-hover table-bordered table-condensed">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.ID</td>
<td>@item.Title</td>
</tr>
} </tbody>
</table> <div class="row">
@Component.Invoke("Test", 2);
</div> <h1>
Total: @service.GetCount()
</h1>

在 startup.cs 中注册该类:

     public void ConfigureServices(IServiceCollection services)
{
// Add EF services to the services container.
services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(); // Add Identity services to the services container.
services.AddDefaultIdentity<ApplicationDbContext, ApplicationUser, IdentityRole>(Configuration); // Add MVC services to the services container.
services.AddMvc(); services.AddTransient<StatisticsService>();
// Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
// You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
// services.AddWebApiConventions(); }

运行 看效果:

七 总结

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. libevent学习文档(二)eventbase相关接口和参数

    Setting up a default event_base The event_base_new() function allocates and returns a new event base ...

  2. AI技术说:人工智能相关概念与发展简史

    作为近几年的一大热词,人工智能一直是科技圈不可忽视的一大风口.随着智能硬件的迭代,智能家居产品逐步走进千家万户,语音识别.图像识别等AI相关技术也经历了阶梯式发展.如何看待人工智能的本质?人工智能的飞 ...

  3. Redis安装部署【转】

    Redis是一种高级key-value数据库.它跟memcached类似,不过数据可以持久化,而且支持的数据类型很丰富.有字符串,链表,集 合和有序集合.支持在服务器端计算集合的并,交和补集(diff ...

  4. 分布式监控系统开发【day37】:监控数据如何优化(六)

    一.数据如何存储方案讨论 1.一个服务存所有主机 2.一台主机的所有服务 3.所有的服务一分钟存一次? 数据量大,浏览器会卡住, 4.最终方案如下 二.解决方案存在问题 1.只能存7天如何处理? 超过 ...

  5. vue 一开始

    项目安装 vue init webpack bibivue-router Y npm run dev

  6. Python urllib urlretrieve函数解析

    Python urllib urlretrieve函数解析 利用urllib.request.urlretrieve函数下载文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 Ur ...

  7. nginx 与 tomcat 组合搭建web服务

    部分内容转自 http://www.cnblogs.com/naaoveGIS/ 1. Web服务 nginx是常用的web服务器,用于获取静态资源,类似的服务器还有apache. tomcat是基于 ...

  8. Codeforces 620C EDU C.Pearls in a Row ( set + greed )

    C. Pearls in a Row There are n pearls in a row. Let's enumerate them with integers from 1 to n from ...

  9. 铺地砖|状压DP练习

    有一个N*M(N<=5,M<=1000)的棋盘,现在有1*2及2*1的小木块无数个,要盖满整个棋盘,有多少种方式?答案只需要mod1,000,000,007即可. //我也不知道这道题的来 ...

  10. Linux下不能挂载NTFS格式硬盘/U盘

    如果大家以后在Ubuntu系统下面遇到NTFS格式的移动硬盘哪个分区不能挂载的话,可以尝试sudo ntfsfix /dev/你相应的分区