Razor Pagesで変数(プロパティ)の値をHTMLタグとして出力するコードを紹介します。
Html.Raw
を利用します。何も指定しない状態でプロパティの値を画面に表示した場合の動作を確認します。
下記のRazorPageを作成します。
@page
@model HtmlGenerate.Pages.SimpleHtmlOutputModel
@{
}
<html>
<head></head>
<body>
<p>テストページ</p>
@Model.OutputMessage
<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 HtmlGenerate.Pages
{
public class SimpleHtmlOutputModel : PageModel
{
public string OutputMessage { get; set; }
public void OnGet()
{
OutputMessage = "<h2>タイトル</h2>";
OutputMessage += "<p>メッセージ1です。あいうえお。</p>";
OutputMessage += "<p>メッセージ2です。ABCDEFG</p>";
}
}
}
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 HtmlGenerate
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
OutputMessage
プロパティを宣言します。OnGetメソッドで、OutputMessageプロパティに値を設定します。 public class SimpleHtmlOutputModel : PageModel
{
public string OutputMessage { get; set; }
public void OnGet()
{
OutputMessage = "<h2>タイトル</h2>";
OutputMessage += "<p>メッセージ1です。あいうえお。</p>";
OutputMessage += "<p>メッセージ2です。ABCDEFG</p>";
}
}
@Model.OutputMessage
を記述し、ページモデルクラスのOutputMessage
プロパティの値をページに表示します。
Startup.csファイルで、RazorPageへのルーティングを実装しています。
(アプリケーションルート)/SimpleHtmlOutput
URLにアクセスします。下図のページが表示されます。HTMLタグをプロパティの文字列として設定していますが、タグの文字がそのまま画面に表示され、HTMLの書式として反映されていないことが確認できます。
Html.Raw
を利用します。@Html.Raw()
メソッドの引数にページモデルのプロパティの値を与えます。@page
@model HtmlGenerate.Pages.SimpleHtmlOutputModel
@{
}
<html>
<head></head>
<body>
<p>テストページ</p>
@Html.Raw(Model.OutputMessage)
<p>テストページ</p>
</body>
</html>
Html.Raw()
メソッドの引数にHTMLのタグ文字列を与えると、タグの文字列をHTMLの書式として表現できます。(アプリケーションルート)/SimpleHtmlOutput
URLにアクセスします。下図のページが表示されます。タグの文字列がHTMLの書式として表現され、文字の大きさや段落として表現できていることが確認できます。