0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ASP.NET Core モデルのプロパティをView(cshtml)で表示する

Posted at

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>

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?