当前位置: 移动技术网 > IT编程>开发语言>.net > 详解ASP.NET Core 2.0 视图引擎(译)

详解ASP.NET Core 2.0 视图引擎(译)

2017年11月17日  | 移动技术网IT编程  | 我要评论

g版美人鱼,新母女狩猎者,101外卖网

问题

如何在asp.net core 2.0中使用razor引擎来创建视图?

答案

新建一个空项目,修改startup.cs,添加mvc服务和请求中间件:

public void configureservices(iservicecollection services)

{

  services.addmvc();

}

 

public void configure(iapplicationbuilder app, ihostingenvironment env)

{

  if (env.isdevelopment())

  {

    app.usedeveloperexceptionpage();

  }

 

  app.usemvc(routes =>

  {

    routes.maproute(

      name: "default",

      template: "{controller=home}/{action=index}/{id?}");

  });

}   

添加controllers目录,并添加homecontroller控制器:

public class homecontroller : controller

{

  public iactionresult index()

  {

    return view();

  }

} 

添加views/home目录,并添加razor视图index.cshtml:

@{

  var birthdate = new datetime(1930, 8, 26);

}

 

<strong>hello mvc razor</strong>

 

<p>james bond, you were born @birthdate.tostring("yyyy-mm-dd")</p>

 

<p>james bond is about @((datetime.now - birthdate).days / 365) years old</p>

 

<p>@("<strong>hello world</strong>")</p>

 

<p>@html.raw("<strong>james@bond.com</strong>")</p>

 

@{

  var ishungry = true;

  var gender = 0;

  ienumerable<string> friends = new[] { "thor", "hulk", "iron man" };

  var technology = "asp.net mvc";

  var count = technology.count();

}

 

<p>

  @if (ishungry)

  {

    <text>i'm hungry</text>

  }

  else

  {

    <text>i'm full</text>

  }

</p>

 

 

@switch (gender)

{

  case 0:

    <p>male</p>

    break;

  case 1:

    <p>female</p>

    break;

  default:

    break;

}

 

@for (int i = 0; i < technology.length; i++)

{

  @technology[i].tostring().toupper()

}

 

<ul>

  @foreach (var item in friends)

  {

    <li>@item</li>

  }

</ul>

 

@try

{

  var a = 1; var b = 0;

  var result = a / b; // divide by zero

}

catch (exception ex)

{

  <p>@ex.message</p>

} 

此时的目录结构如下所示:

运行,此时页面显示:

讨论

当控制器返回viewresult时,asp.net core中间件会查找并执行razor模板(.cshtml文件)。razor模板使用c#和html的混合语法来生成最终的html页面。

查找视图

当viewresult执行时,它会按照如下顺序查找视图所在路径:

1. views/[controller]/[action].cshtml

2. views/shared/[action].cshtml

如果模板文件名和控制器方法的名称不一致,可以在viewresult中通过参数来指定视图模板的名称:

public iactionresult aboutme()

{

  return view("bio");

}  

razor语法

html标签会原封不动的渲染到最终的html页面中:

<strong>hello mvc razor</strong>   

通过@符号从html过渡到c#代码。c#代码块可以用如下结构包含起来:

@{

  var birthdate = new datetime(1930, 8, 26);

} 

c#表达式可以直接通过@符号来输出到最终html页面:

<p>james bond, you were born @birthdate.tostring("yyyy-mm-dd")</p> 

或者用@( //c#表达式 )来包含起来:

<p>james bond is about @((datetime.now - birthdate).days / 365) years old</p> 

razor默认会对c#表达式进行html编码,观察下面的razor代码以及生成到页面上的html结构:

<p>@("<strong>hello world</strong>")</p> 

<p><strong>hello world</strong></p> 

@html.raw可以避免c#表达式被html编码,如下所示:

<p>@html.raw("<strong>james@bond.com</strong>")</p> 
 

<p><strong>james@bond.com</strong></p> 

    

控制结构

razor视图中,我们可以在c#代码块中使用各种控制结构,比如@if, @switch, @for, @foreach, @while, @do while和@try。具体示例可以查看views/home/index.cshtml代码。

指令

razor视图会被转化为继承自razorpage的c#类(内部实现,对用户透明)。而指令可以改变这些类或者视图引擎的行为。常用的指令有:

@using

向生成的c#类添加一个using指令。类似于普通的c#类,这个指令用来导入命名空间。

@model

指定传入razorpage的泛型类型t。当控制器返回viewresult时,可以通过参数来指定模型类型。然后在视图页面中通过model属性来获取模型实例。

 @inject

用来向视图注入服务(首先需要在startup中在服务容器中注册此服务)。你需要提供服务类型和名称(视图中通过此名称访问服务)。视图的依赖注入用于为视图提供强类型的数据查询服务,否则我们就需要动态的viewdata或者viewbag属性来实现。

视图的依赖注入

下面通过一个较完整的示例来讲解@using,@model和@inject指令的用法。

首先创建一个服务:

public interface igreeter

{

  string greet(string firstname, string surname);

}

 

public class greeter : igreeter

{

  public string greet(string firstname, string surname)

  {

    return $"hello {firstname} {surname}";

  }

}  

在startup的服务容器中注册此服务:

public void configureservices(iservicecollection services)

{

  services.addscoped<igreeter, greeter>();

 

  services.addmvc();

} 

创建一个模型:

public class aboutviewmodel

{

  public string firstname { get; set; }

  public string surname { get; set; }

} 

从控制器方法中返回模型实例:

public class homecontroller : controller

{

  public iactionresult index()

  {

    return view();

  }

 

  public iactionresult aboutme()

  {

    var model = new aboutviewmodel

    {

      firstname = "tahir",

      surname = "naushad"

    };

    return view("bio", model);

  }

} 

现在我们可以在视图中使用模型和服务了:

 @using razorengine.models

@model aboutviewmodel

@inject igreeter greeterservice

 

<p>@greeterservice.greet(model.firstname, model.surname)</p> 

运行,此时页面显示:

原文:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网