承接上一章,這邊來提一下Bind Attribute,他的主要目的為,不需要每個屬性都要做Binding,也可能是為了安全性考量,其中,排除的屬性是設為 null 或預設值,我們只要在Action參數Attribute做需要Bind的設定即可。
Bind Attribute
承接上一張的程式,我們為Id跟Name套上Bind屬性看看
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AddNew([Bind("Id,Name")IronMan model)
{
ViewBag.result = $@"
IronMan id : {model.Id}
IronMan Name : {model.Name}
IronMan Birth Date : {model.BirthDate}
";
return View();
}
}
MVC提供多種Attribute來客製化Model Binding,例如:
[BindRequired]
public int Age { get; set; }
複雜的屬性Binding
有時候屬性可能是一個類別,例如Resume(履歷),可能會有很多其他屬性
Model
namespace IronMan.Models
{
public class IronMan
{
[Display(Name = "Id")]
public int Id { get; set; }
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "Birth Date")]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
public Resume Resume { get; set; }
}
public class Resume{
public string Company { get; set; }
public int Salary { get; set; }
}
}
View
承接上一章的表單範例,我們只要設定兩個Resume下的欄位即可
<div class="form-group">
<label asp-for="Resume.Company" class="control-label"></label>
<input asp-for="Resume.Company" class="form-control" />
<span asp-validation-for="Resume.Company" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Resume.Salary" class="control-label"></label>
<input asp-for="Resume.Salary" class="form-control" />
<span asp-validation-for="Resume.Salary" class="text-danger"></span>
</div>
Controller
submit後,Resume(class)就可以接到參數
[HttpPost]
public IActionResult AddNew(IronMan model)
{
ViewBag.result = $@"
IronMan id : {model.Id}
IronMan Name : {model.Name}
IronMan Birth Date : {model.BirthDate}
Resume Company : {model.Resume.Company}
Resume Salary : {model.Resume.Salary}
";
return View();
}
陣列屬性Binding
我們也可以Binding陣列,設定方式也很直覺,比方說IronMan可以填寫4個Job
Model
先加入Array屬性的Jobs
public string[] Jobs { get; set; }
View端
最多可填寫四筆,迴圈先印出四個textbox
<div class="form-group">
<label asp-for="Jobs" class="control-label"></label>
<ul>
@for (int i = 0; i < 4; i++)
{
<li><input asp-for="Jobs[i]" class="form-control" /></li>
}
</ul>
</div>
Controller端
負責接收資料即可
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AddNew(IronMan model)
{
ViewBag.result = $@"
IronMan id : {model.Id}
IronMan Name : {model.Name}
IronMan Birth Date : {model.BirthDate}
IronMan Jobs : {string.Join(",", model.Jobs)}
";
return View();
}
}
參考資料
https://docs.microsoft.com/zh-tw/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1