Controller的參數的傳遞
Url請求
GET: http://www.xxx.com?id=1&name=張三
POST:
(1)http://www.xxx.com
(2)Body 傳遞form等。
這種請求是一種協議,瀏覽器按照協議傳,代碼解析
參數傳遞的實際代碼
區別post和get以及frombody或者fromform
using KevinTest001.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace KevinTest001.Controllers
{
/***
*#Kevin asp.net
*
* asp.net mvc
* asp.net core mvc
* 綁定模型機制把獲取http的請求的參數 (get,post) action的參數對應的參數進行綁定
* id參數 index(int id)
* IBindModel原理底層
* ModelState 模型綁定狀態
*/
public class BindController:BaseController
{
//localhost:60201/bind/index?id=7&name=張三
//public IActionResult Index(int id,string name) #Kevin 多個參數的時候傳遞比較麻煩
//public IActionResult Index(Person person) #Kevin 可以按照Person裏面的字段比配傳遞接收
//public IActionResult Index([FromBody]Person person) //#kevin指定只能從頁面Body傳遞,不能從Url來
//默認是get方法
public IActionResult Index()
{
return View();
}
//#支持重載
/*
[HttpPost]
public IActionResult Index([FromForm]Person person) //http://localhost:60154/bind/index
{
return View();
}
*/
//#支持重載
/*
[HttpPost]
public IActionResult Index(Person person,List<int> ids) //獲取html頁面的列表
{
return View();
}
*/
[HttpPost]
public IActionResult Index(Person person) //獲取html頁面的列表
{
/*
* if (String.IsNullOrEmpty(person.name))
{
return Content("請輸入名字");
}
*/
ModelState.Remove("name"); //#Kevin 這種就可以去除驗證了,使不同頁面引用同一模型的時候去掉驗證
bool flag = ModelState.IsValid; //看前臺頁面滿足模型驗證否?
if (ModelState.IsValid)
{
return Content("數據驗證不通過");
}
return View();
}
}
}
數據驗證:
數據必須填寫之類的
在Model中寫
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace KevinTest001.Models
{
public class Person
{
public string id { get; set; }
//[Required] //#Kevin 這個是說字段必須填寫的
[Required(ErrorMessage = "請輸入名稱")] //#Kevin 錯誤提示
[StringLength(2, ErrorMessage = "長度超過2位")] //#校驗長度
//[EmailAddress],時間、正則表達式驗證等
public string name { get; set; }
}
}