現(xiàn)在,ASP.NET MVC 6 支持注入類到視圖中,和VC類不同的是,對(duì)類是公開的、非嵌套或非抽象并沒有限制。在這個(gè)例子中,我們創(chuàng)建了一個(gè)簡(jiǎn)單的類,用于統(tǒng)計(jì)×××事件、已完成事件和平均優(yōu)先級(jí)的服務(wù)。
我們提供的服務(wù)有:成都網(wǎng)站建設(shè)、成都做網(wǎng)站、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、山丹ssl等。為千余家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的山丹網(wǎng)站制作公司
StatisticsService 類代碼設(shè)計(jì)如下:
using System.Linq;
using System.Threading.Tasks;
using TodoList.Models;
namespace TodoList.Services
{
public class StatisticsService
{
private readonly ApplicationDbContext db;
public StatisticsService(ApplicationDbContext context)
{
db = context;
}
public async TaskGetCount()
{
return await Task.FromResult(db.TodoItems.Count());
}
public async TaskGetCompletedCount()
{
return await Task.FromResult(
db.TodoItems.Count(x => x.IsDone == true));
}
public async TaskGetAveragePriority()
{
return await Task.FromResult(
db.TodoItems.Average(x =>
(double?)x.Priority) ?? 0.0);
}
}
}
@inject TodoList.Services.StatisticsService Statistics
添加標(biāo)記調(diào)用 StatisticsService:
@Html.ActionLink("Create New Todo", "Create", "Todo")
@await Component.InvokeAsync("PriorityList", 4, true)Stats
Items: @await Statistics.GetCount() Completed:@await Statistics.GetCompletedCount() Average Priority:@await Statistics.GetAveragePriority()
以下是該文件的完整代碼:
@inject TodoList.Services.StatisticsService Statistics
@{
ViewBag.Title = "Home Page";
}
ASP.NET vNext
@if (Model.Count == 0){No Todo Items
}else{
TODO @foreach (var todo in Model){@todo.Title @Html.ActionLink("Details", "Details", "Todo", new { id = todo.Id }) |@Html.ActionLink("Edit", "Edit", "Todo", new { id = todo.Id }) |@Html.ActionLink("Delete", "Delete", "Todo", new { id = todo.Id })}}@Html.ActionLink("Create New Todo", "Create", "Todo")@await Component.InvokeAsync("PriorityList", 4, true)Stats
Items: @await Statistics.GetCount() Completed:@await Statistics.GetCompletedCount() Average Priority:@await Statistics.GetAveragePriority()
// This method gets called by the runtime.
public void ConfigureServices(IServiceCollection services)
{
// Add EF services to the services container.
services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext();
// Add Identity services to the services container.
services.AddDefaultIdentity(Configuration);
// Add MVC services to the services container.
services.AddMvc();
services.AddTransient();
}
以下是效果圖:
發(fā)布應(yīng)用到公有云,你需要申請(qǐng) Microsoft Azure 帳號(hào),如果沒有,可以通過以下鏈接注冊(cè):activate your MSDN subscriber benefits 或 sign up for a free trial.
數(shù)據(jù)庫(kù)服務(wù)器是一個(gè)寶貴的資源。最好使用現(xiàn)有服務(wù)器進(jìn)行測(cè)試和開發(fā)。然而由于沒有密碼校驗(yàn)機(jī)制,密碼輸入錯(cuò)誤時(shí)不會(huì)有錯(cuò)誤提示,只有在應(yīng)用實(shí)際訪問數(shù)據(jù)庫(kù)時(shí)才會(huì)報(bào)錯(cuò)。
原文鏈接:http://www.asp.net/vnext/overview/aspnet-vnext/vc#inj
ASP.NET 5系列教程 (一):領(lǐng)讀新特性
ASP.NET 5系列教程 (二):Hello World
ASP.NET 5系列教程 (三):view components介紹