在HTML/CSS 中,我們經(jīng)常用HTML來布局和填充內容,用CSS來添加效果,修飾內容和布局,使整個頁面變得更好看。
即在<head></head>標簽內添加CSS樣式表的鏈接:
代碼展示如下:
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Make a Table Frame</title> <link rel="stylesheet" type="text/css" href="CSS/tableframe.css" > </head>
定義:
對帶有指定屬性的 HTML 元素設置樣式。
注意:
只有在規(guī)定了 !DOCTYPE 時,IE7 和 IE8 才支持屬性選擇器。在 IE6 及更低的版本中,不支持屬性選擇。
功能:
“選擇器”指明了{}中的“樣式”的作用對象,也就是“樣式”作用于網(wǎng)頁中的哪些元素。
CSS中的選擇器有三個:
標簽選擇器、class類選擇器、id選擇器
1.標簽選擇器樣式表:a{}、 div{}、table{} ...
{對全局所有的選中類型標簽的樣式修改}
2.class類選擇器 樣式表: .class{}
{在HTML中每個標簽都可以同時綁定多個類名,每個標簽都可以設置class;同一個界面中class是不可重復}
3. id選擇器樣式表: #d1 {}
{每個標簽都可有id,每個頁面不可重復id,}
【一個HTML標簽只能綁定一個id屬性,一個HTML標簽可以綁定多個class屬性】
單純選擇<div>標簽的時候 是對全局的的(所有的)<div>進行修飾;
選擇器優(yōu)先級:
id選擇器>class類選擇器>標簽選擇器
所以有id和class 選擇器的標簽將不會被覆蓋。交叉時是按照優(yōu)先級覆蓋顯示的。
單純的HTML 表格表單內容
標題<caption>標簽:
表格的標題<caption>的內容填充(HTML):
<caption> 表格標題</caption>
標題<caption>的樣式修飾(CSS)
table.formdata caption { text-shadow: #FF00ff; text-align: center; padding-bottom: 6px; font-weight: bold; }
其他<table>標簽相關內容可參考 HTML中表格的實例應用 一文。
form在網(wǎng)頁中主要負責數(shù)據(jù)采集功能。
一個表單有三個基本組成部分:
(1)表單標簽:包含了處理表單數(shù)據(jù)所用CGI程序的URL以及數(shù)據(jù)提交到服務器的方法。
(2)表單域:包含了文本框、密碼框、隱藏域、多行文本框、復選框、單選框、下拉選擇框和文件上傳框等。
(3)表單按鈕:提交按鈕、復位按鈕和一般按鈕;用于將數(shù)據(jù)傳送到服務器上的CGI腳本或者取消輸入。還可以用表單按鈕來控制其他定義了處理腳本的處理工作。
定義:
<input> 標簽規(guī)定用戶可輸入數(shù)據(jù)的輸入字段。
根據(jù)不同的 type 屬性,輸入字段有多種形態(tài)。輸入字段可以是文本字段、復選框、密碼字段、單選按鈕、按鈕等等
語法代碼:
<input type="value" >
實例代碼:
<td><input type="text" name="Mainboard 6月" id="Mainboard 6月"></td>
關系展示:
實例代碼:
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Add Data" class="btn">
<input type="reset" value= "Reset All" class="btn">
</p>
實例展示:
<input>標簽的其他屬性值:
input標簽外是否添加form標簽需要按情形區(qū)分:
應用場景的區(qū)別:
1.所有向后臺提交數(shù)據(jù)(包括原生和ajax提交)的<input>都建議用<form>包裹.
2.如果只是用來做前臺交互效果則不推薦使用form包裹。
但提交數(shù)據(jù)時,其實也可以不用form包裹input標簽:
1.如果有form標簽,在點擊提交銨鈕時,瀏覽器自動收集參數(shù),并打包一個http請求到服務器,完成表單提交。在這一過程中,瀏覽器會根據(jù)method的不同,將參數(shù)編碼后,放在urI中(get),或者放在請求的data中(post)。然后發(fā)送到服務器。
2.如果沒有form,post方式的提交要使用ajax手工完成。get方式的提交需要自己拼接url。
<form>表單其他相關內容可參考 HTML中 表單 的應用實例 一文。
最后,附帶一下該可輸入的EXCEL表格的源碼。
HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Make a Table Frame</title> <link rel="stylesheet" type="text/css" href="CSS/tableframe.css" > </head> <body image=""> <form method="psot"> <table border="1px" class="formdata"> <caption>電腦配件管理表2018年5月-8月</caption> <tr> <th></th> <th scope="col">5月</th> <th scope="col">6月</th> <th scope="col">7月</th> <th scope="col">8月</th> </tr> <tr> <th scope="row">Hard Disk</th> <td><input type="text" name="Hard Disk 5月" id="Hard Disk 5月"></td> <td><input type="text" name="Hard Disk 6月" id="Hard Disk 6月"></td> <td><input type="text" name="Hard Disk 7月" id="Hard Disk 7月"></td> <td><input type="text" name="Hard Disk 8月" id="Hard Disk 8月"></td> </tr> <tr> <th scope="row">Mainboard</th> <td><input type="text" name="Mainboard 5月" id="Mainboard 5月"></td> <td><input type="text" name="Mainboard 6月" id="Mainboard 6月"></td> <td><input type="text" name="Mainboard 7月" id="Mainboard 7月"></td> <td><input type="text" name="Mainboard 8月" id="Mainboard 8月"></td> </tr> <tr> <th scope="row">Case</th> <td><input type="text" name="Case 5月" id="Case 5月"></td> <td><input type="text" name="Case 6月" id="Case 6月"></td> <td><input type="text" name="Case 7月" id="Case 7月"></td> <td><input type="text" name="Case 8月" id="Case 8月"></td> </tr> <tr> <th scope="row">Power</th> <td><input type="text" name="Power 5月" id="Power 5月"></td> <td><input type="text" name="Power 6月" id="Power 6月"></td> <td><input type="text" name="Power 7月" id="Power 7月"></td> <td><input type="text" name="Power 8月" id="Power 8月"></td> </tr> <tr> <th scope="row">CPU Fan</th> <td><input type="text" name="CPU Fan 5月" id="CPU Fan 5月"></td> <td><input type="text" name="CPU Fan 6月" id="CPU Fan 6月"></td> <td><input type="text" name="CPU Fan 7月" id="CPU Fan 7月"></td> <td><input type="text" name="CPU Fan 8月" id="CPU Fan 8月"></td> </tr> <tr> <th scope="row">Total</th> <td><input type="text" name="Total 5月" id="Total 5月"></td> <td><input type="text" name="Total 6月" id="Total 6月"></td> <td><input type="text" name="Total7月" id="Total 7月"></td> <td><input type="text" name="Total 8月" id="Total 8月"></td> </tr> </table> <p> <input type="submit" name="btnSubmit" id="btnSubmit" value="Add Data" class="btn"> <input type="reset" value= "Reset All" class="btn"> </p> </form> </body> </html>
CSS code :
body { font-family: Arial; /*background-image: url(image/mainroad.jpg) no-repeat;*/ background-color: #00ff00; background-size: 100%; } table.formdata { width: 300px; height: 150px; border: 2px solid #F00; border-collapse: collapse; font-family: Arial; } table.formdata caption { text-shadow: #FF00ff; text-align: center; padding-bottom: 6px; font-weight: bold; } table.formdata th { border:1px solid #be34hc; background-color: #E2E2E2; color:#000000; text-aglin:center; font-weight: normal; padding: 2px 8px 2px 6px; margin: 0px; } table.formdata input { width: 100px; padding: 1px 3px 1px 3px; margin: 0px; border:none; font-family: Arial; } .btn { width:100px; background-color: #FF00ee; border:1px solid #00f2f2; font-family: Arial; }
本文部分內容來自網(wǎng)絡,如有侵權,請聯(lián)系修改。
昨天我們在《使用HTML添加表格3(間距與顏色)——零基礎自學網(wǎng)頁制作》(目錄在結尾)中學習了設置單元格以及其中內容的空間間距和背景顏色。
其中添加列向單元格背景顏色只需要修改對應的<tr>標簽中的style屬性,而修改行向標簽需要修改不同<tr></tr>標簽中的<td>標簽的style屬性,這樣操作起來就非常的麻煩,那有沒有簡便的修改行向單元格背景顏色的方法呢?
當然有!
開發(fā)團隊給出了<colgroup><col></col></colgroup>這樣的組合來解決這個問題,下面讓我們詳細學習。
<colgroup></colgroup>標簽是一個給行向單元格打組的標簽,在頁面中不會顯示。
<col></col>標簽是來具體設置行向單元格數(shù)量和顏色的標簽。
示例代碼如下:
<colgroup><col span = "1" style="background-color:#ff0000;"></col></colgroup>
這段代碼添加到"第一個頁面.html"當中就可以,具體代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<title>第一個網(wǎng)頁</title>
</head>
<body>
<h1>第一個網(wǎng)頁</h1><hr>
<h2>表格元素</h2><hr>
<table border="1" width="100%">
<thead>
<tr>
<td colspan="2">表格的頭部信息</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="2">表格的腳部信息</td>
<tr>
</tfoot>
<tbody>
<caption>表格標題</caption>
<colgroup>
<col span = "1" style="background-color:#ff0000;"></col>
</colgroup>
<tr>
<th>姓名</th>
<th>年齡</th>
</tr>
<tr>
<td>一列一行</td>
<td>一列二行</td>
</tr>
<tr>
<td>二列一行</td>
<td>二列二行</td>
</tr>
</tbody>
</table>
</body>
</html>
頁面效果如圖:
因為第一列和最后一列只有一行所以,也都變紅了。
其中span的數(shù)量代表行數(shù)。
如果把span等號后面的數(shù)改成2,因為表格只有兩行,所以整個表格都紅了。
表格嵌套
我們可以通過向表格中添加表格實現(xiàn)表格嵌套。表格嵌套可以把一個單元格分成行向或列向分割單元格。
代碼示例如下:我們把"一列一行"分割成列向兩個單元格。
<tr><td><table border = "1" width="100%"><tr><td>1</td><td>2</td></tr></table></td>
使用
<table border = "1" width="100%">
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
這段代碼替換文字"一列一行"即可。
頁面效果如圖所示:
留個思考題,大家可以思考一下行向分割單元格怎么寫。
今天的內容結束了。
全部示例代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<title>第一個網(wǎng)頁</title>
</head>
<body>
<h1>第一個網(wǎng)頁</h1><hr>
<h2>表格元素</h2><hr>
<table border="1" width="100%">
<thead>
<tr>
<td colspan="2">表格的頭部信息</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="2">表格的腳部信息</td>
<tr>
</tfoot>
<tbody>
<caption>表格標題</caption>
<colgroup>
<col span = "1" style="background-color:#ff0000;"></col>
</colgroup>
<tr>
<th>姓名</th>
<th>年齡</th>
</tr>
<tr>
<td>
<table border = "1" width="100%">
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
</td>
<td>一列二行</td>
</tr>
<tr>
<td>二列一行</td>
<td>二列二行</td>
</tr>
</tbody>
</table>
</body>
</html>
喜歡的小伙伴請關注我,閱讀中遇到任何問題請給我留言,如有疏漏或錯誤歡迎大家斧正,不勝感激!
學到這里,相信大家已經(jīng)有獨立讀懂HTML代碼說明的能力了,明天我會為大家講解16進制顏色表示方法。之后會給大家推薦html代碼參考手冊的鏈接。如果您是零基礎的話,學完16進制顏色表示方法后,基本上就可以無障礙的閱讀html代碼參考手冊了,如果閱讀起來還是有困難,請繼續(xù)看后面我為大家講解一些常用元素及屬性的文章,已及html中特殊符號的輸入方法,全部做完后再結束這套教程。
如果您有任何疑問或不解歡迎關注并私信我。
HTML序章(學習目的、對象、基本概念)——零基礎自學網(wǎng)頁制作
HTML是什么?——零基礎自學網(wǎng)頁制作
第一個HTML頁面如何寫?——零基礎自學網(wǎng)頁制作
HTML頁面中head標簽有啥用?——零基礎自學網(wǎng)頁制作
初識meta標簽與SEO——零基礎自學網(wǎng)頁制作
HTML中的元素使用方法1——零基礎自學網(wǎng)頁制作
HTML中的元素使用方法2——零基礎自學網(wǎng)頁制作
HTML元素中的屬性1——零基礎自學網(wǎng)頁制作
HTML元素中的屬性2(路徑詳解)——零基礎自學網(wǎng)頁制作
使用HTML添加表格1(基本元素)——零基礎自學網(wǎng)頁制作
使用HTML添加表格2(表格頭部與腳部)——零基礎自學網(wǎng)頁制作
使用HTML添加表格3(間距與顏色)——零基礎自學網(wǎng)頁制作
使用HTML添加表格4(行顏色與表格嵌套)——零基礎自學網(wǎng)頁制作
16進制顏色表示與RGB色彩模型——零基礎自學網(wǎng)頁制作
HTML中的塊級元素與內聯(lián)元素——零基礎自學網(wǎng)頁制作
初識HTML中的<div>塊元素——零基礎自學網(wǎng)頁制作
在HTML頁面中嵌入其他頁面的方法——零基礎自學網(wǎng)頁制作
封閉在家學網(wǎng)頁制作!為頁面嵌入PDF文件——零基礎自學網(wǎng)頁制作
HTML表單元素初識1——零基礎自學網(wǎng)頁制作
HTML表單元素初識2——零基礎自學網(wǎng)頁制作
HTML表單3(下拉列表、多行文字輸入)——零基礎自學網(wǎng)頁制作
HTML表單4(form的action、method屬性)——零基礎自學網(wǎng)頁制作
HTML列表制作講解——零基礎自學網(wǎng)頁制作
為HTML頁面添加視頻、音頻的方法——零基礎自學網(wǎng)頁制作
音視頻格式轉換神器與html視頻元素加字幕——零基礎自學網(wǎng)頁制作
HTML中使用<a>標簽實現(xiàn)文本內鏈接——零基礎自學網(wǎng)頁制作
在ASP.NET Core處理模型有兩個核心的概念
模型綁定分為基礎和高級分別兩篇,在這節(jié)中,我們學習關于模型綁定處理的細節(jié)
我們通過一個例子來了解模型綁定的概念,在Visual Studio 2022 中創(chuàng)建一個ASP.NET Core Web App (Model-View-Controller) 項目,名稱為AspNetCore.ModelBinding
Models & Repository
在Models文件夾下添加一個新的類叫EmployeeDetails.cs,這定義了2個兩個類和一個枚舉:
namespace AspNetCore.ModelBinding.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DOB { get; set; }
public Address HomeAddress { get; set; }
public Role Role { get; set; }
}
public class Address
{
public string HouseNumber { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
public enum Role
{
Admin,
Designer,
Manager
}
}
namespace AspNetCore.ModelBinding.Models
{
public interface IRepository
{
IEnumerable<Employee> Employee { get; }
Employee this[int id] { get; set; }
}
public class EmployeeRepository : IRepository
{
private Dictionary<int, Employee> employee = new Dictionary<int, Employee>
{
[1] = new Employee
{
Id = 1,
Name = "John",
DOB = new DateTime(1980, 12, 25),
Role = Role.Admin
},
[2] = new Employee
{
Id = 2,
Name = "Michael",
DOB = new DateTime(1981, 5, 13),
Role = Role.Designer
},
[3] = new Employee
{
Id = 3,
Name = "Rachael",
DOB = new DateTime(1982, 11, 25),
Role = Role.Designer
},
[4] = new Employee
{
Id = 4,
Name = "Anna",
DOB = new DateTime(1983, 1, 20),
Role = Role.Manager
}
};
public IEnumerable<Employee> Employee => employee.Values;
public Employee this[int id]
{
get
{
return employee.ContainsKey(id) ? employee[id] : ;
}
set
{
employee[id] = value;
}
}
}
}
我們創(chuàng)建repository并且創(chuàng)建4個員工,我們使用4個員工的數(shù)據(jù)幫助我們理解模型綁定的概念
Controllers & Views
using AspNetCore.ModelBinding.Models;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCore.ModelBinding.Controllers
{
public class HomeController : Controller
{
private IRepository repository;
public HomeController(IRepository repo)
{
repository = repo;
}
public IActionResult Index(int id = 1)
{
return View(repository[id]);
}
}
}
@model Employee
@{
ViewData["Title"] = "Index";
}
<h2>Employee</h2>
<table class="table table-bordered align-middle">
<tr><th>Id:</th><td>@Model.Id</td></tr>
<tr><th>Name:</th><td>@Model.Name</td></tr>
<tr><th>Date of Birth:</th><td>@Model.DOB.ToShortDateString()</td></tr>
<tr><th>Role:</th><td>@Model.Role</td></tr>
</table>
注冊Repository作為服務
builder.Services.AddSingleton<IRepository, EmployeeRepository>();
在應用中更新下面代碼:
using ModelBindingValidation.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddSingleton<IRepository, EmployeeRepository>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
...
2 理解模型綁定
ASP.NET Core模型綁定在整個過程發(fā)揮什么作用呢?我們請求的URL包含了employee id的值(給與第三段的URL是1) /Home/Index/1
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
public IActionResult Index(int id = 1)
{
return View(repository[id]);
}
模型綁定會從下面3個地方查詢值:
1 表單數(shù)據(jù)值
2 路由變量
3 查詢字符串
這是為什么Employee 為2的員工被顯示,因為在查詢字符串Id的值(即1)之前框架在路由變量中發(fā)現(xiàn)了Id(即2)值,因此2的值被提供給action方法參數(shù),如果我們打開URL-Home/Index?id=3,然而Employee Id為3的員工將被顯示:
如果ASP.NET Core在這三個地方?jīng)]有發(fā)現(xiàn)綁定的值,會發(fā)生什么呢?– 表單數(shù)據(jù)值,路由變量&查詢字符串,在這種情況下,它將根據(jù)action方法定義的類型提供默認值,這些默認值是:
2 string類型為""
3 時間類型為01-01-0001 00:00:00
4 float類型為0
public IActionResult Index(int id)
{
if (id == 0)
id = 1;
return View(repository[Convert.ToInt32(id)]);
}
我們數(shù)據(jù)中沒有員工Id為0,因此我們在if代碼塊中賦值為1,這將幫助我們阻止運行時錯誤,我們可以通過使用Try-Catch 塊處理運行時錯誤
注意可空類型的默認值為,現(xiàn)在修改Index方法有一個able int類型參數(shù),代碼如下:
public IActionResult Index(int? id)
{
if (id == )
id = 1;
return View(repository[Convert.ToInt32(id)]);
}
運行你的應用程序并且進入URL– /Home/Index,現(xiàn)在通過斷點來檢查id的值, 這時你將發(fā)現(xiàn)它的值為
4 模型綁定簡單類型
public IActionResult Index(int? id)
{
if (id == )
id = 1;
return View(repository[Convert.ToInt32(id)]);
}
如果你收到要給URL,Id值是字符串 像– /Home/Index/John 在這種情況下,框架將嘗試把John轉換到int值,這時不能轉化,因此action 方法接收到id的參數(shù)為
模型綁定查找公共屬性從下面三個地方:
在Home Controller中添加Create方法,這兩個方法如下:
public IActionResult Create() => View();
[HttpPost]
public IActionResult Create(Employee model) => View("Index", model);
模型綁定的功能是從Http請求中提取Employee類公共屬性,并且將它提供給Create方法的參數(shù),該方法傳遞Employee模型對象到默認View
@model Employee
@{
ViewData["Title"] = "Create Employee";
}
<h2>Create Employee</h2>
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="Id"></label>
<input asp-for="Id" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
</div>
<div class="form-group">
<label asp-for="DOB"></label>
<input asp-for="DOB" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Role"></label>
<select asp-for="Role" class="form-control"
asp-items="@new SelectList(Enum.GetNames(typeof(Role)))"></select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<input asp-for="Id" class="form-control" />
Name屬性被綁定通過下面這種方式
<input asp-for="Name" class="form-control" />
下面2張圖片顯示了填充和提交的表單:
6 復雜對象包含復雜對象
EmployeeDetails.cs類包含了名稱為HomeAddress公共屬性,這個屬性是一個Address類型,因此復雜對象包含另一個復雜對象案例
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DOB { get; set; }
public Address HomeAddress { get; set; }
public Role Role { get; set; }
}
public class Address
{
public string HouseNumber { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
綁定HomeAddress屬性時,模型綁定處理過程和前面的相同:
更新Create.cshtml視圖文件綁定HomeAddress類型所有屬性,代碼如下:
@model Employee
@{
ViewData["Title"] = "Create Employee";
}
<h2>Create Employee</h2>
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="Id"></label>
<input asp-for="Id" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
</div>
<div class="form-group">
<label asp-for="DOB"></label>
<input asp-for="DOB" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Role"></label>
<select asp-for="Role" class="form-control"
asp-items="@new SelectList(Enum.GetNames(typeof(Role)))"></select>
</div>
<div class="form-group">
<label asp-for="HomeAddress.HouseNumber"></label>
<input asp-for="HomeAddress.HouseNumber" class="form-control" />
</div>
<div class="form-group">
<label asp-for="HomeAddress.City"></label>
<input asp-for="HomeAddress.City" class="form-control" />
</div>
<div class="form-group">
<label asp-for="HomeAddress.Street"></label>
<input asp-for="HomeAddress.Street" class="form-control" />
</div>
<div class="form-group">
<label asp-for="HomeAddress.PostalCode"></label>
<input asp-for="HomeAddress.PostalCode" class="form-control" />
</div>
<div class="form-group">
<label asp-for="HomeAddress.Country"></label>
<input asp-for="HomeAddress.Country" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
當綁定HomeAddress屬性時候,我們必須包含"HomeAddress",看Helper標簽asp-for="HomeAddress.HouseNumber" 綁定HouseNumber屬性,我們也為另一些屬性使用這種綁定
@model Employee
@{
ViewData["Title"] = "Index";
}
<h2>Employee</h2>
<table class="table table-sm table-bordered table-striped">
<tr><th>Id:</th><td>@Model.Id</td></tr>
<tr><th>Name:</th><td>@Model.Name</td></tr>
<tr><th>Date of Birth:</th><td>@Model.DOB.ToShortDateString()</td></tr>
<tr><th>Role:</th><td>@Model.Role</td></tr>
<tr><th>House No:</th><td>@Model.HomeAddress?.HouseNumber</td></tr>
<tr><th>Street:</th><td>@Model.HomeAddress?.Street</td></tr>
<tr><th>City:</th><td>@Model.HomeAddress?.City</td></tr>
<tr><th>Postal Code:</th><td>@Model.HomeAddress?.PostalCode</td></tr>
<tr><th>Country:</th><td>@Model.HomeAddress?.Country</td></tr>
</table>
現(xiàn)在,運行應用程序并且進入URL– /Home/Create, 填充并提交表單,我們將發(fā)現(xiàn)address類型屬性的顯示,顯示圖片如下:
檢查源代碼
下面是瀏覽器為html生成的源代碼
<div class="form-group">
<label for="HomeAddress_HouseNumber">HouseNumber</label>
<input class="form-control" type="text" id="HomeAddress_HouseNumber" name="HomeAddress.HouseNumber" value="" />
</div>
<div class="form-group">
<label for="HomeAddress_City">City</label>
<input class="form-control" type="text" id="HomeAddress_City" name="HomeAddress.City" value="" />
</div>
<div class="form-group">
<label for="HomeAddress_Street">Street</label>
<input class="form-control" type="text" id="HomeAddress_Street" name="HomeAddress.Street" value="" />
</div>
<div class="form-group">
<label for="HomeAddress_PostalCode">PostalCode</label>
<input class="form-control" type="text" id="HomeAddress_PostalCode" name="HomeAddress.PostalCode" value="" />
</div>
<div class="form-group">
<label for="HomeAddress_Country">Country</label>
<input class="form-control" type="text" id="HomeAddress_Country" name="HomeAddress.Country" value="" />
</div>
HouseNumber輸入控件獲取屬性名字的值HomeAddress.HouseNumber,然而id屬性的值變?yōu)镠omeAddress_HouseNumber,相同的方式,City輸入控件獲取name屬性的值,然而id的屬性的值為 HomeAddress_City
string houseNo = Request.Form["HomeAddress.HouseNumber"];
[Bind(Prefix)]特性能修改復雜類型模型綁定的默認行為,讓我們通過一個例子來理解,創(chuàng)建一個名為PersonAddress.cs的模型類使用下面代碼:
namespace AspNetCore.ModelBinding.Models
{
public class PersonAddress
{
public string City { get; set; }
public string Country { get; set; }
}
}
[ ]
public IActionResult DisplayPerson(PersonAddress personAddress)
{
return View(personAddress);
}
下一步,修改Create視圖中asp-action標簽的值,將該值設置為DisplayPerson,代碼如下:
<form asp-action="DisplayPerson" method="post">
...
</form>
@model PersonAddress
@{
ViewData["Title"] = "Person";
}
<h2>Person</h2>
<table class="table table-sm table-bordered table-striped">
<tr><th>City:</th><td>@Model.City</td></tr>
<tr><th>Country:</th><td>@Model.Country</td></tr>
</table>
現(xiàn)在運行你的應用程序,并且進入URL- /Home/Create,填充表單并且點擊提交按鈕
模型綁定失敗的原因是因為City和Country輸入控件屬性Name包含了字符串HomeAddress 前綴,在瀏覽器中檢查輸入控件源代碼
<input class="form-control" type="text" id="HomeAddress_City" name="HomeAddress.City" value="">
<input class="form-control" type="text" id="HomeAddress_Country" name="HomeAddress.Country" value="">
為了解決這個問題,我們在action方法的參數(shù)中應用[Bind(Prefix)],告訴ASP.NET Core 基于HomeAddress前綴完成模型綁定
public IActionResult DisplayPerson
([Bind(Prefix = nameof(Employee.HomeAddress))] PersonAddress personAddress)
{
return View(personAddress);
}
再次提交表單,這次我們將發(fā)現(xiàn)City和Country值并將他們顯示在瀏覽器,看下面圖片:
使用[Bind]選擇性的綁定屬性
public IActionResult DisplayPerson([Bind(nameof(PersonAddress.City), Prefix = nameof(Employee.HomeAddress))] PersonAddress personAddress)
{
return View(personAddress);
}
我們可以使用另外一種方法實現(xiàn)相同的功能,在PersonAddress類的Country屬性上使用 [BindNever] 特性,BindNever指定的屬性模型綁定將被忽略
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace AspNetCore.ModelBinding.Models
{
public class PersonAddress
{
public string City { get; set; }
[ ]
public string Country { get; set; }
}
}
8 模型綁定上傳文件
我們通過模型綁定技術完成上傳文件功能,這里我們必須做3件事情:
1 在View中添加input type=”file”控件
2 在html表單的標簽中添加enctype="multipart/form-data"特性
3 在action方法中添加IFormFile類型參數(shù),使用該參數(shù)綁定上傳文件
我們創(chuàng)建一個上傳文件的特性,添加一個新的Controller并且命名為FileUploadController.cs. 代碼給與如下:
using Microsoft.AspNetCore.Mvc;
namespace ModelBindingValidation.Controllers
{
public class FileUploadController : Controller
{
private IWebHostEnvironment hostingEnvironment;
public FileUploadController(IWebHostEnvironment environment)
{
hostingEnvironment = environment;
}
public IActionResult Index() => View();
[ ]
public async Task<IActionResult> Index(IFormFile file)
{
string path = Path.Combine(hostingEnvironment.WebRootPath, "Images/" + file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return View((object)"Success");
}
}
}
添加一個IWebHostEnvironment 的依賴用來獲取"wwwroot"文件夾的全部路徑, Index方法通過模型綁定技術將上傳的文件綁定到IFormFile類型參數(shù)
方法內部將文件保存到應用程序wwwroot/Images文件夾內
為了能夠正常工作你確保在wwwroot目錄下創(chuàng)建Images文件夾,接下來在 Views/FileUpload文件夾內添加Index文件,代碼如下:
@model string
@{
ViewData["Title"] = "Upload File";
}
<h2>Upload File</h2>
<h3>@Model</h3>
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="file" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
總結:
參考文獻
https://www.yogihosting.com/aspnet-core-model-binding/
*請認真填寫需求信息,我們會在24小時內與您取得聯(lián)系。