标签:man from list 文件夹 home project mod use mapr
配置应用程序管道
public void Configure(IApplicationBuilder app){ app.UseDeveloperExceptionPage(); app.UseMvc(m => { m.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action="Index"}); }); }
连接mvc各个组件,添加相关依赖项
public void ConfigureServices(IServiceCollection services){ services.AddMvc(); }
新特性Inject
a.定义类或服务
using System.Linq; using System.Threading.Tasks; namespace MVCCoreDemo.Models { public class HeroStats { private HeroManager _manager = new HeroManager(); public async Task<int> GetHeroCount() { return await Task.FromResult(_manager.GetAll.Count()); } public async Task<int> GetHeroCountByType(string type) { return await Task.FromResult(_manager.GetHeroesByType(type).Count); } } }
b.在视图中使用
@model IEnumerable<MVCCoreDemo.Models.DOTAHero> @inject MVCCoreDemo.Models.HeroStats Stats <h3>My Favorite DOTA 2 Heroes</h3> <ul> @foreach (var p in Model) { <li>@($"{p.Name} {p.Type}")</li> } </ul> <div> <h4>Stats</h4> <p>Number of Strength Heroes: @await Stats.GetHeroCountByType("strength")</p> <p>Number of Agility Heroes: @await Stats.GetHeroCountByType("agility")</p> <p>Number of Intelligence Heroes: @await Stats.GetHeroCountByType("intelligence")</p> <p>Total Heroes Heroes: @await Stats.GetHeroCount()</p> </div>
c.依赖注入类或服务
public void ConfigureServices(IServiceCollection services){ services.AddMvc(); services.AddTransient<MVCCoreDemo.Models.HeroStats>(); }
新特性View Components
遵循ViewComponent结尾约定
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MVCCoreDemo.Models; namespace MVCCoreDemo.ViewComponents { public class HeroListViewComponent: ViewComponent { public async Task<IViewComponentResult> InvokeAsync(string type){ var heroes = await GetHeroesAsync(type); return View(heroes); } private Task<IEnumerable<DOTAHero>> GetHeroesAsync(string type){ return Task.FromResult(GetHeroes(type)); } private IEnumerable<DOTAHero> GetHeroes(string type){ HeroManager HM = new HeroManager(); return HM.GetHeroesByType(type); } } }
文件夹创建遵循Components文件夹,子文件夹命名遵循去除ViewCompont
视图默认Default.cshtml
@model IEnumerable<MVCCoreDemo.Models.DOTAHero> <h3>@Model.First().Type Heroes</h3> <ul> @foreach (var p in Model) { <li>@p.Name</li> } </ul>
调用ViewComponent
<div> @await Component.InvokeAsync("HeroList", new { type = "agility" }) </div>
ASP.NET Core: Getting Started with ASP.NET MVC Core(一)
标签:man from list 文件夹 home project mod use mapr
原文地址:http://www.cnblogs.com/Sam--Wang/p/6284181.html