Detailed explanation ASP.NET Core 2.0 view engine

Time:2020-11-15

problem

How to ASP.NET Using the razor engine to create views in core 2.0?

answer

Create an empty item, modify Startup.cs Add MVC service and request middleware


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?}");

  });

}   

Add controllers directory and add homecontroller controller:


public class HomeController : Controller

{

  public IActionResult Index()

  {

    return View();

  }

} 

Add the views / home directory and add the razor view 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>[email protected]</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>

} 

The directory structure is as follows:

Run, the page displays:

discuss

When the controller returns viewresult, ASP.NET The core middleware finds and executes the razor template (. Cshtml file). The razor template uses a mixed syntax of C ා and HTML to generate the final HTML page.

Find view

When viewresult is executed, it will find the path of the view in the following order:

1. Views/[Controller]/[Action].cshtml

2. Views/Shared/[Action].cshtml

If the name of the template file is inconsistent with the name of the controller method, you can specify the name of the view template through the parameter in viewresult:


public IActionResult AboutMe()

{

  return View("Bio");

}  

Razor grammar

The HTML tag will be rendered to the final HTML page intact:


<strong>Hello MVC Razor</strong>   

Transition from HTML to C ා code through @ symbol. The C ා code block can be contained in the following structure:


@{

  var birthDate = new DateTime(1930, 8, 26);

} 

C ා expression can be directly output to the final HTML page through @ symbol:


<p>James Bond, you were born @birthDate.ToString("yyyy-MM-dd")</p> 

Or use @ (/ / C # expression) to include:


<p>James Bond is about @((DateTime.Now - birthDate).Days / 365) years old</p> 

Razor will encode the C ා expression by default. Observe the following razor code and the HTML structure generated on the page:


<p>@("<strong>Hello World</strong>")</p> 

<p>&lt;strong&gt;Hello World&lt;/strong&gt;</p> 

@ Html.Raw You can avoid HTML encoding of C ා expressions, as follows:


<p>@Html.Raw("<strong>[email protected]</strong>")</p> 
 

<p><strong>[email protected]</strong></p> 

    

control structure

In the razor view, we can use various control structures in the C ා code block, such as @ if, @ switch, @ for, @ foreach, @ while, @ do while and @ try. For specific examples, you can view views / home/ Index.cshtml code.

instructions

The razor view is converted to a C ා class (internal implementation, transparent to users) inherited from razorpage. Instructions can change the behavior of these classes or view engines. The commonly used instructions are:

@using

Add a using instruction to the generated C ා class. Similar to the normal C ා class, this instruction is used to import the namespace.

@model

Specifies the generic type t passed in to razorpage. When the controller returns viewresult, the model type can be specified by a parameter. Then get the model instance through the model property in the view page.

 @inject

Used to inject a service into the view (you need to register the service in the service container in startup first). You need to provide the type and name of the service (the name is used to access the service in the view). Dependency injection of views is used to provide strongly typed data query services for views, otherwise we need dynamic viewdata or viewbag properties to implement.

Dependency injection of views

The following is a complete example to explain the usage of @ using, @ model and @ inject instructions.

First create a service:


public interface IGreeter

{

  string Greet(string firstname, string surname);

}

 

public class Greeter : IGreeter

{

  public string Greet(string firstname, string surname)

  {

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

  }

}  

Register this service in startup’s services container:


public void ConfigureServices(IServiceCollection services)

{

  services.AddScoped<IGreeter, Greeter>();

 

  services.AddMvc();

} 

Create a model:


public class AboutViewModel

{

  public string Firstname { get; set; }

  public string Surname { get; set; }

} 

Return the model instance from the controller method:


public class HomeController : Controller

{

  public IActionResult Index()

  {

    return View();

  }

 

  public IActionResult AboutMe()

  {

    var model = new AboutViewModel

    {

      Firstname = "Tahir",

      Surname = "Naushad"

    };

    return View("Bio", model);

  }

} 

Now we can use models and services in Views:


 @using RazorEngine.Models

@model AboutViewModel

@inject IGreeter GreeterService

 

<p>@GreeterService.Greet(Model.Firstname, Model.Surname)</p> 

Run, the page displays:

Source code download

Original text: https://tahirnaushad.com/2017/08/23/asp-net-core-2-0-mvc-razor/

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.