VS2019创建新项目:ASP.NET Core Web 应用程序:ASP.NET Core Web 应用(模型-视图-控制器)
主要结构介绍:
有四个项目创建时自带的,不用管:
Program.cs与Startup.cs是启动文件
appsettings.json与Properties/launchSettings.json是运行与整体配置
我们主要操作的有四个文件夹:
wwwroot存前端css/js/img等文件
Models是模型,主要是进行后端的数据存储管理
Views是页面,主要是进行前端的页面布局显示
Controllers是控制器,主要是处理请求
下面是基础使用例程:(没有用数据库,没装SQL_Server)
右击Models文件夹->添加->新建项->类,创建GuestResponse.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace cjweb.Models{
public class GuestResponse{ //让login.html与HomeController中的login函数联动
[Required(ErrorMessage="input your name please")]
public string username { get; set; }
[Required(ErrorMessage = "input your password please")]
public string password { get; set; }
[Required(ErrorMessage = "select your sex please")]
public string sex { get; set; }
}
}
重写Controllers/HomeController.cs
using cjweb.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace cjweb.Controllers{
public class HomeController : Controller{
public IActionResult index(){ // http://localhost:56802/
ViewBag.Greeting = DateTime.Now.Hour; // 传送当前小时值
return View("index"); // 自动寻找index.cshtml
}
[HttpPost] // 不写的话默认是HttpGet
public IActionResult login(GuestResponse data){ // http://localhost:56802/home/login
if (ModelState.IsValid){ // 如果符合验证
string x = data.username; // 通过GuestResponse类对象接收view的参数
string y = data.password; // 通过GuestResponse类对象接收view的参数
string z = data.sex; // 通过GuestResponse类对象接收view的参数
ViewBag.last_submit = x + y + z; // 通过ViewBag类对象给view传送参数
}
return View(); // 默认找与函数名同名的,即index.cshtml
}
[HttpGet]
public IActionResult login(){ // http://localhost:56802/home/login
return View(); // 这个是首次访问时执行的,提交表单见post
}
}
}
删掉Views/Home下的模板文件,右击Views/Home文件夹->添加->新建项->Razor视图-空,自己写index.cshtml与login.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>index</title>
</head>
<body>
<div>
<br />这里是首页
<br />这里是后端给前端数据:
@if (@ViewBag.Greeting < 12){
@:上午好
}
else{
@:下午好
}
<br /><a asp-action="login">这里是网站内跳转</a>
</div>
</body>
</html>
@model cjweb.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>login</title>
</head>
<body>
<div>
login
</div>
<form asp-action="login" method="post">
<input asp-for="username" />
<input asp-for="password" />
<select asp-for="sex">
<option value="male">male</option>
<option value="female">female</option>
</select>
<button type="submit">submit</button>
</form>
<hr/>
@ViewBag.last_submit
</body>
</html>