ASP.NET學習筆記
阿新 • • 發佈:2021-02-03
技術標籤:2021年研究生學習筆記
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>