RazorPages アプリケーションでHTMLタグを表示するとタグが文字列として画面に表示される現象について紹介します。
現象の確認
コード
以下のRazor Pageとコードを記述します。
@page
@model OutputPageContent.Pages.SimpleTextOutputModel
@{
}
<html>
<head>
<style type="text/css">
.Frame {
border: solid 1px #0094ff;
}
</style>
</head>
<body>
<p>出力のデモ</p>
<div class="Frame">
@Model.ContentText
</div>
<p>水色の枠にページモデルで設定したコンテンツが表示されます。</p>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace OutputPageContent.Pages
{
public class SimpleTextOutputModel : PageModel
{
public string ContentText { get; set; }
public void OnGet()
{
ContentText = "<div style=\"color:#008782;font-size:2rem\" >コンテンツです。ABCDEFG</div>";
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OutputPageContent
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
解説
ページモデルクラスのOnGetメソッドで
ContentText
プロパティにページに表示したい文字列を代入します。
RazorPageのcshtmlファイルの
@Model.ContentText
でページモデルクラスの
ContentText
プロパティの値を表示します。
実行結果
上記のRazor Pagesアプリケーションを起動し
(アプリケーションルート)/SimpleTextOutput
のURLをWebブラウザでアクセスします。
下図のページが表示されます。
文字列にHTMLのタグを含む文字列を設定していますが、HTMLタグの部分も文字列としてページ内に表示されてしまいます。
対処方法
文字列をHTMLのタグの文字列として出力する場合は、Html.Rawメソッドを利用します。
Html.Rawメソッドの書式や動作の詳細は
こちらの記事を参照してください。
SimpleTextOutput.cshtmlファイルのページ内の下記のコードを変更します。
<div class="Frame">
@Model.ContentText
</div>
<div class="Frame">
@Html.Raw(Model.ContentText)
</div>
実行結果
変更後、プロジェクトを実行し
(アプリケーションルート)/SimpleTextOutput
のURLをWebブラウザでアクセスします。
下図のページが表示されます。出力する文字列がHTMLタグの文字列として処理されて表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2021-02-18
作成日: 2021-02-17