目录
创建项目
dotnet new webapp -o app
该命令可用dotnet -h
、dotnet [command] -h
查看帮助
运行
cd app
dotnet run
用Vistual studio 2022 开始一个“hello World”
创建项目
打开VS2022->创建新项目->选择“ASP.NET Core Web 应用->填写项目名称为“HelloWorld”->...
项目文件
launchSettings.json
该文件包含一些和技术方案无关的启动配置项
wwwroot 文件夹
静态资源文件,如:css、js、html文件
Pages 文件夹
Razor页面和其对应的.cs代码文件,有点类似Winform窗体的前后端分离方式,一个Bazor页面通常(非必须)对应一个.cs代码文件(.cshtml.cs)。Razor文件(.cshtml)是包含C#代码的HTML文件,当项目运行时,结合.cs文件,在服务端生成html文件并返回给浏览器
Pages\Shared 文件夹
页面模板文件
appsettings.json
项目配置文件(此类文件可配置多个,根据条件选择使用哪个)
Program.cs
程序入口。可在这里配置web宿主(builder.Build())、中间件(app.UseXXX)、注入项(builder.Services.AddXXX)等
增加数据库实体
新建数据库表People
新建实体类
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
appsettings.json中添加连接字符串
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"HelloWorldDbContext": "Server=localhost\\SQLEXPRESS;Database=HelloWorld;User Id=sa;Password=12345"
}
}
增加DbContext
public class HelloWorldDbContext : DbContext
{
public HelloWorldDbContext(DbContextOptions<HelloWorldDbContext> options) : base(options)
{
}
public DbSet<Person> People { get; set; }
}
注入DbContext
// Program.cs
builder.Services.AddDbContext<HelloWorldDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("HelloWorldDbContext")));
增加列表页
删除VS默认生成的cshtml文件,在Page文件夹下添加Razor页,命名为Index.cshtml。在indexModel类中加入代码:
public class IndexModel : PageModel
{
private readonly HelloWorldDbContext _dbContext;
public IndexModel(HelloWorldDbContext dbContext)
{
_dbContext = dbContext;
}
public IList<Person> People { get; set; }
public void OnGet()
{
People = _dbContext.People.ToList();
}
}
修改Index.cshtml:
@page
@model HelloWorld.Pages.IndexModel
<h1>Index</h1>
<table class="table">
<thead>
<tr>
<th>@Html.DisplayNameFor(m => m.People[0].Name)</th>
<th>@Html.DisplayNameFor(m => m.People[0].Age)</th>
<th>@Html.DisplayNameFor(m => m.People[0].Birthday)</th>
</tr>
</thead>
<tbody>
@foreach(var person in Model.People)
{
<tr>
<td>@Html.DisplayFor(item => person.Name) </td>
<td>@Html.DisplayFor(item => person.Age) </td>
<td>@Html.DisplayFor(item => person.Birthday) </td>
</tr>
}
</tbody>
</table>
修改_Layout.cshtml文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - HelloWorld</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/HelloWorld.styles.css" asp-append-version="true" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">HelloWorld</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/People">People</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2022 - HelloWorld - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
运行之:
增加Create页
在Pages文件夹下添加Razor页面:Create.cshtml。如下:
@page
@model HelloWorld.Pages.CreateModel
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Person.Name" class="control-label"></label>
<input asp-for="Person.Name" class="form-control" />
<span asp-validation-for="Person.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Person.Age" class="control-label"></label>
<input asp-for="Person.Age" class="form-control" />
<span asp-validation-for="Person.Age" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Person.Birthday" class="control-label"></label>
<input asp-for="Person.Birthday" class="form-control" />
<span asp-validation-for="Person.Birthday" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary"/>
</div>
</form>
</div>
<div>
<a asp-page="Index">Back to List</a>
</div>
</div>
@section Scripts{
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Create.cshtml.cs类如下:
using HelloWorld.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace HelloWorld.Pages
{
public class CreateModel : PageModel
{
private readonly HelloWorldDbContext _dbContext;
public CreateModel(HelloWorldDbContext dbContext)
{
_dbContext = dbContext;
}
[BindProperty]
public Person Person { get; set; }
public IActionResult OnGet()
{
return Page();
}
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
_dbContext.People.Add(Person);
_dbContext.SaveChanges();
return RedirectToPage("Index");
}
}
}
Index.cshtml中增加代码:
<p>
<a asp-page="Create">Create</a>
</p>