ASP.NET Core Razor Pages - ViewData to javascript alert

Joyce 100 Reputation points
2024-08-09T10:02:29.8766667+00:00

Hello,

In this sample application, I was trying to pop an alert OnPost but text got garbled.

However, in the page itself, a simultaneous inline display did render text correctly.

@page
@model IndexModel
@{
	ViewData["Title"] = "Home page";
}
<form method="post">
	<input type="submit" />
	<br />
	<br />
	<span>@ViewData["Message"]</span>
</form>
@section scripts {
	<script type="text/javascript">
		window.onload = function () {
			alert("@ViewData["Message"]");
		};
	</script>
}
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApplication1.Pages
{
	public class IndexModel : PageModel
	{
		public void OnPost()
		{
			ViewData["Message"] = "ABCD 甲乙丙丁";
		}
	}
}

3

4

I studied a similar case https://github.com/dotnet/aspnetcore/issues/47479

but that did not resolve mine, both my .cshtml and .cs have identical encoding.

5

Thanks in advance for any advice or direction.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,806 questions
0 comments No comments
{count} votes

Accepted answer
  1. JasonPan - MSFT 6,851 Reputation points Microsoft External Staff
    2024-08-09T12:01:45.9233333+00:00

    Hi @Joyce,

    Please use @Html.Raw(ViewData["Message"]) instead of @ViewData["Message"]. Here is my sample code and test result.

    @section scripts {
    	<script type="text/javascript">
    		window.onload = function () {
    			//alert("@ViewData["Message"]");
    			alert("@Html.Raw(ViewData["Message"])");
    		};
    	</script>
    }
    

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Jason

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.