1
0

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.

.NET MVCのViewのRazor構文でif文を使い、返す値を単に文字列にする方法

Posted at

Viewのファイルを操作するにあたり、困ったことがあった。

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Password)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.done)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

という構文があったときに、item.doneはbool型の値なので、
trueの場合は、済
falseの場合は、未
を表示したい場合、<td>タグの中を<div>などのhtmlタグで囲まずに使う方法が分からなかったので調べてみた。

方法は2つ。

文字列を<text>タグで囲む

        <td>
            @if(item.done){
               <text></text>
            } else {
         <text></text>
            }
        </td>

文字の前に「@:」をつける

        <td>
            @if(item.done){
               @:
            } else {
         @:
            }
        </td>

参考記事

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?