整合營銷服務商

          電腦端+手機端+微信端=數(shù)據(jù)同步管理

          免費咨詢熱線:

          HTML/CSS中可直接輸數(shù)據(jù)的表格

          lt;table>和<form>結合效果圖:

          在HTML/CSS 中,我們經(jīng)常用HTML來布局和填充內容,用CSS來添加效果,修飾內容和布局,使整個頁面變得更好看。


          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>
          

          CSS選擇器

          定義:

          對帶有指定屬性的 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)先級覆蓋顯示的。


          <table>部分:電腦配件管理表2018年5月-8月

          單純的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>部分:

          form在網(wǎng)頁中主要負責數(shù)據(jù)采集功能。

          一個表單有三個基本組成部分:

          (1)表單標簽:包含了處理表單數(shù)據(jù)所用CGI程序的URL以及數(shù)據(jù)提交到服務器的方法。

          (2)表單域:包含了文本框、密碼框、隱藏域、多行文本框、復選框、單選框、下拉選擇框和文件上傳框等。

          (3)表單按鈕:提交按鈕、復位按鈕和一般按鈕;用于將數(shù)據(jù)傳送到服務器上的CGI腳本或者取消輸入。還可以用表單按鈕來控制其他定義了處理腳本的處理工作。

          <input>標簽

          定義:

          <input> 標簽規(guī)定用戶可輸入數(shù)據(jù)的輸入字段。

          根據(jù)不同的 type 屬性,輸入字段有多種形態(tài)。輸入字段可以是文本字段、復選框、密碼字段、單選按鈕、按鈕等等

          語法代碼:

          <input type="value" >
          

          實例代碼:

          <td><input type="text" name="Mainboard 6月" id="Mainboard 6月"></td>
          

          關系展示:


          <input>中 submit屬性 和reset屬性

          實例代碼:

          <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>標簽?

          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完整學習目錄

          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)頁制作

          么是模型綁定?模型綁定是從HTTP請求獲取數(shù)據(jù)的一個過程并且將他們提供給Action方法的參數(shù),模型包含了構成應用程序業(yè)務邏輯的數(shù)據(jù),它們包含了數(shù)據(jù)庫或者另外數(shù)據(jù)源中的數(shù)據(jù)

          在ASP.NET Core處理模型有兩個核心的概念

          1 Model Binding – 從HTTP請求提取數(shù)據(jù)的一個過程,并將數(shù)據(jù)提供給Action方法的參數(shù)
          2 Model Validation – 處理模型屬性驗證的一個過程以至于未驗證的實體不能進入數(shù)據(jù)庫

          模型綁定分為基礎和高級分別兩篇,在這節(jié)中,我們學習關于模型綁定處理的細節(jié)

          1 ASP.NET Core 模型綁定例子

          我們通過一個例子來了解模型綁定的概念,在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 }}
            在Models文件夾下創(chuàng)建一個新的文件Repository.cs,定義接口并實現(xiàn)該接口:
            • 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

              在Controllers文件夾下編輯HomeController.cs文件,通過依賴注入從構造函數(shù)中獲取EmployeeRepository 倉儲類,更新HomeController.cs 文件代碼如下:
              • 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]); } }}
                在Views->Home文件下編輯Index.cshtml 視圖文件以至于它能接收到Employee模型并綁定employee屬性在HTML表格,Index 代碼如下:
                • @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作為服務

                  在Program.cs類中注冊EmployeeRepository 服務,以至于控制器能夠通過依賴注入訪問這個類,代碼如下:
                  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();...
                    現(xiàn)在運行項目并且進入URL– /Home/Index/1,將看到employee為1的員工編號顯示在瀏覽器,圖片如下:

                    2 理解模型綁定

                    ASP.NET Core模型綁定在整個過程發(fā)揮什么作用呢?我們請求的URL包含了employee id的值(給與第三段的URL是1) /Home/Index/1

                    在Program.cs 類中有默認路由,路由指定了3個URL段,Id是變量
                    • app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}" );
                      現(xiàn)在,我們看到Index方法有一個Id參數(shù)
                      • public IActionResult Index(int id = 1){ return View(repository[id]);}
                        ASP.NET Core模型綁定處理過程從URL中獲取的Id值,并且將Id值通過參數(shù)提供給action方法

                        模型綁定會從下面3個地方查詢值:

                        1 表單數(shù)據(jù)值

                        2 路由變量

                        3 查詢字符串

                        從表單數(shù)據(jù)開始檢查,然后路由變量,最后是查詢字符串,在這種情況下,框架如果沒有在表單數(shù)據(jù)中發(fā)現(xiàn)Id的值, 接著會檢查路由變量,發(fā)現(xiàn)有個路由變量的值叫Id,然后停止搜索, 接下來不會搜索查詢字符串
                        搜索順序是非常重要,如果我們打開URL– /Home/Index/2?id=1 ,然而我們將會看到Employee Id 為2的記錄, 如下圖所示:

                        這是為什么Employee 為2的員工被顯示,因為在查詢字符串Id的值(即1)之前框架在路由變量中發(fā)現(xiàn)了Id(即2)值,因此2的值被提供給action方法參數(shù),如果我們打開URL-Home/Index?id=3,然而Employee Id為3的員工將被顯示:

                        在這種情況下,框架沒有發(fā)現(xiàn)Id的值在URL段,因此它將搜索查詢字符串發(fā)現(xiàn)Id為3的值
                        3 模型綁定默認值

                        如果ASP.NET Core在這三個地方?jīng)]有發(fā)現(xiàn)綁定的值,會發(fā)生什么呢?– 表單數(shù)據(jù)值,路由變量&查詢字符串,在這種情況下,它將根據(jù)action方法定義的類型提供默認值,這些默認值是:

                        1 int類型為0

                        2 string類型為""

                        3 時間類型為01-01-0001 00:00:00

                        4 float類型為0

                        在Index方法代碼中我們測試一下模型綁定默認值:
                        • public IActionResult Index(int id){ if (id == 0) id = 1; return View(repository[Convert.ToInt32(id)]);}
                          我們把參數(shù)id默認值移除掉,接下來我們在Index方法中打斷點,然后運行應用程序并且進入URL – /Home/Index,注意在這個url中沒有給定第三個參數(shù)employee id,因此 現(xiàn)在模型綁定將提交默認值,當斷點命中時,我們將鼠標移動到id變量上檢查一下值,你將看到值0,如下圖所示:

                          當ASP.NET Core 沒有給employee id 值,因此它會為id參數(shù)綁定默認值,Id參數(shù)是int類型,默認值是0,因此模型綁定提供了默認值為0
                          你能獲取到它 – 如果Id參數(shù)類型修改為string,然而模型綁定將給與默認值""

                          我們數(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 模型綁定簡單類型

                            當ASP.NET Core 綁定簡單類型時,將會把值轉換為方法的參數(shù)類型,簡單類型是– string,int,bool,float,datetime,decimal等
                            讓我們通過一個簡單的例子來了解一下:
                            • public IActionResult Index(int? id){ if (id == ) id = 1; return View(repository[Convert.ToInt32(id)]);}
                              Index方法參數(shù)是int類型因此ASP.NET Core 框架會自動轉換url中id段變量的值到int值
                              案例 1 : 針對 URL – /Home/Index/1
                              當強求的URL包含的id值為int,像– /Home/Index/1 框架會成功轉換1的值到int,因此方法參數(shù)會收到參數(shù)為1
                              案例 2 : 針對 URL – /Home/Index/John

                              如果你收到要給URL,Id值是字符串 像– /Home/Index/John 在這種情況下,框架將嘗試把John轉換到int值,這時不能轉化,因此action 方法接收到id的參數(shù)為

                              5 模型綁定復雜類型
                              當action方法的參數(shù)是復雜類型,像類對象,然而模型綁定會指定綁定每個復雜類型的公共屬性

                              模型綁定查找公共屬性從下面三個地方:

                              1 表單數(shù)據(jù)
                              2 路由變量
                              3 查詢字符串
                              這個是非常重要的感念,你將在你的項目中再次使用,面試時也經(jīng)常問到這個問題,因此我們創(chuàng)建一個例子理解它

                              在Home Controller中添加Create方法,這兩個方法如下:

                              • public IActionResult Create() => View();[HttpPost]public IActionResult Create(Employee model) => View("Index", model);
                                HTTP GET版本的Create方法選擇默認View并且沒有傳遞任何模型給它,HTTP POST 版本的Create方法有一個Employee參數(shù)的類型(是一個復雜類型)

                                模型綁定的功能是從Http請求中提取Employee類公共屬性,并且將它提供給Create方法的參數(shù),該方法傳遞Employee模型對象到默認View

                                接下來在Views->Home 文件夾下創(chuàng)建Create 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>
                                  這個View包含了一個表單并且綁定了Employee實體一些公共屬性,當表單被提交這些值將被提交到HTTP POST版本的Create方法
                                  Create方法需要Employee對象的參數(shù),因此模型綁定過程首先從表單數(shù)據(jù)中查找Employee對象的每個公共屬性的值(Id, Name, DOB, Role)
                                  表單數(shù)據(jù)包含了這些值,使用asp-for幫助標簽作為輸入元素,例如-示例–id屬性綁定到輸入控件,如下所示
                                  <input asp-for="Id" class="form-control" />

                                  Name屬性被綁定通過下面這種方式

                                  <input asp-for="Name" class="form-control" />
                                  模型綁定會把這些值綁定到Employee對象的屬性,將Employee對象傳遞給Create方法的參數(shù),Create方法使用模型綁定技術獲取employee類型的參數(shù)值
                                  asp-for 是一個幫助標簽,你可以獲取到更多的關于內置幫助標簽在ASP.NET Core
                                  Post版本的Create方法調用Index視圖,將Employee對象作為Model傳遞給View,現(xiàn)在運行應用程序并且進入URL– /Home/Create,在表單中輸入所有值并點擊提交按鈕,我們會看到填充的值顯示在瀏覽器上

                                  下面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屬性時,模型綁定處理過程和前面的相同:

                                    1 查找所有HomeAddress的公共屬性(即 HouseNumber, Street, City, PostalCode, Country)
                                    2 在表單數(shù)據(jù)中搜索這些公共屬性的值,注意路由&查詢字符串變量不能包含復雜類型

                                    更新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屬性,我們也為另一些屬性使用這種綁定

                                      編輯Index視圖顯示HomeAddress對象所有屬性,代碼如下:
                                      • @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

                                          在C#代碼中我們也能獲取HouseNumber值在action 方法通過使用Request.Form方法,代碼如下:
                                          string houseNo = Request.Form["HomeAddress.HouseNumber"];
                                          針對另外一些值也是相同的方式
                                          7 使用[Bind(Prefix)]特性綁定復雜類型

                                          [Bind(Prefix)]特性能修改復雜類型模型綁定的默認行為,讓我們通過一個例子來理解,創(chuàng)建一個名為PersonAddress.cs的模型類使用下面代碼:

                                          • namespace AspNetCore.ModelBinding.Models{ public class PersonAddress { public string City { get; set; } public string Country { get; set; } }}
                                            接下來,在HomeController類中添加一個新的action方法叫DisplayPerson
                                            • [HttpPost]public IActionResult DisplayPerson(PersonAddress personAddress){ return View(personAddress);}

                                              下一步,修改Create視圖中asp-action標簽的值,將該值設置為DisplayPerson,代碼如下:

                                              • <form asp-action="DisplayPerson" method="post"> ...</form>
                                                現(xiàn)在,意味著當我們在表單中輸入數(shù)據(jù)并且提交表單時,數(shù)據(jù)將被提交到DisplayPerson方法 ,在Views->Home文件夾創(chuàng)建一個DisplayPerson視圖,這個視圖包含PersonAddress類型,并顯示城市和國家在模型對象
                                                DisplayPerson視圖代碼如下:
                                                • @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沒有包含任何值,模型綁定失敗了,看如下圖:

                                                  模型綁定失敗的原因是因為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前綴完成模型綁定

                                                因此改變DisplayPerson 方法包含[Bind(Prefix = nameof(Employee.HomeAddress))]顯示如下:
                                                • public IActionResult DisplayPerson([Bind(Prefix = nameof(Employee.HomeAddress))] PersonAddress personAddress){ return View(personAddress);}

                                                  再次提交表單,這次我們將發(fā)現(xiàn)City和Country值并將他們顯示在瀏覽器,看下面圖片:

                                                  使用[Bind]選擇性的綁定屬性

                                                  我們可以選擇性的綁定屬性,Bind()方法的第一個參數(shù)提供包含模型綁定中的所有屬性的名稱(用逗號分隔的列表中),那意味著剩下的屬性將不被綁定
                                                  修改DisplayPerson方法代碼,綁定方法包含City屬性
                                                  • public IActionResult DisplayPerson([Bind(nameof(PersonAddress.City), Prefix = nameof(Employee.HomeAddress))] PersonAddress personAddress){ return View(personAddress);}
                                                    測試一下該方法,你將看到僅僅City值顯示,如下圖所示:

                                                    我們可以使用另外一種方法實現(xiàn)相同的功能,在PersonAddress類的Country屬性上使用 [BindNever] 特性,BindNever指定的屬性模型綁定將被忽略

                                                    • using Microsoft.AspNetCore.Mvc.ModelBinding;namespace AspNetCore.ModelBinding.Models{ public class PersonAddress { public string City { get; set; } [BindNever] 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(); [HttpPost] 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>
                                                          瀏覽器看上如下:

                                                          總結:

                                                          在ASP.NET Core中模型綁定是一個重要的感念,開發(fā)人員能夠非常容易的在Views和Controllers之間傳輸數(shù)據(jù),在這節(jié)文章中,我們通過例子來了解模型綁定原理
                                                          源代碼地址
                                                          https://github.com/bingbing-gui/Asp.Net-Core-Skill/tree/master/Fundamentals/AspNetCore.ModelBinding/AspNetCore.ModelBinding

                                                          參考文獻

                                                          https://www.yogihosting.com/aspnet-core-model-binding/


          主站蜘蛛池模板: 成人精品一区二区激情| 午夜福利一区二区三区高清视频 | 成人毛片一区二区| 不卡无码人妻一区三区音频| 一区二区三区在线观看视频| 国产一区二区三区视频在线观看| 成人精品视频一区二区三区尤物| 无码少妇丰满熟妇一区二区| 少妇人妻精品一区二区| 午夜在线视频一区二区三区| 精品一区二区三人妻视频| 爆乳无码AV一区二区三区| 国产午夜精品一区二区三区极品| 日韩福利视频一区| 女人和拘做受全程看视频日本综合a一区二区视频 | 亚洲一区二区三区无码影院| 亚洲欧洲一区二区三区| 在线精品国产一区二区三区| a级午夜毛片免费一区二区| 国产色综合一区二区三区 | 亚洲AV无码一区二区三区人| 在线精品亚洲一区二区| 国产精品盗摄一区二区在线| 无码国产精品一区二区免费vr| 日本片免费观看一区二区 | 亚洲av色香蕉一区二区三区蜜桃| 日本精品夜色视频一区二区| 亚洲日韩AV一区二区三区中文 | 亚洲一区二区三区久久| 高清国产精品人妻一区二区| 久久精品一区二区东京热| 视频一区二区精品的福利| 大伊香蕉精品一区视频在线| 97精品国产一区二区三区| 亚洲一区二区成人| 国产精品免费一区二区三区四区| 一区二区三区四区视频在线| 免费人妻精品一区二区三区| 精品一区二区三区在线视频观看| 国语精品一区二区三区| 国产福利一区二区三区|