ASP.NET Coreのビューでモデルのプロパティを表示する方法です。
モデルの作成
コンタクトフォームのモデルを作成します。[DisplayName("お名前")]
は、モデルのプロパティに付与できるデータアノテーションです。指定の仕方によって、オプションの様に様々な機能や制約を付与することができます。
Contact.cs
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace asp_blog.Models
{
public class Contact
{
[Required]
[DisplayName("お名前")]
public string ContactName { get; set; }
[Required]
[DisplayName("メールアドレス")]
public string ContactEmail { get; set; }
[DisplayName("件名")]
public string ContactTitle { get; set; }
[Required]
[DisplayName("お問い合わせ内容")]
public string ContactDetail { get; set; }
}
}
Viewの作成
@model
に続けてモデルを指定することで、ビューの中で名前解決してモデルを呼び出し、データをバインドします。
Contacs.cshtml
@model asp_blog.Models.Contact
<table>
<tr>
<th>@Html.LabelFor(model => model.ContactName)</th>
<td>@Html.TextBoxFor(model => model.ContactName)</td>
</tr>
<tr>
<th>@Html.LabelFor(model => model.ContactEmail)</th>
<td>@Html.TextBoxFor(model => model.ContactEmail)</td>
</tr>
<tr>
<th>@Html.LabelFor(model => model.ContactTitle)</th>
<td>@Html.TextBoxFor(model => model.ContactTitle)</td>
</tr>
<tr>
<th>@Html.LabelFor(model => model.ContactDetail)</th>
<td>@Html.TextBoxFor(model => model.ContactDetail)</td>
</tr>
</table>