I have a problem with transfer value from method "OnPostAsync" to Register.cshtml. ViewBag doesn't work. How to resolve this problem.

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");
    if (ModelState.IsValid)
    {
        var db = new ApplicationDbContext(_optionsBuilder.Options);
        var email = db.Users.Where(s => s.Email == Input.Email);
        if (email.Count() != 0)
        {
            ViewBag.pom = 100; // this doesn't work
            ViewData["duplicateEmail"] = "Email is already taken";
            return Page();
        }

...
@{
    ViewData["Title"] = "Register";
}

<h2>@ViewData["Title"]</h2>

<div class="row">
    <div class="col-md-4">
        <form asp-route-returnUrl="@Model.ReturnUrl" method="post">
            <h4>Create a new account.</h4>
            <h4>@ViewData["duplicateEmail"] error: @ViewBag.pom</h4>
            <hr />
...

2 Answers

1
Kirk Larkin On Best Solutions

According to the docs:

ViewBag isn't available in Razor Pages.

For more information around why isn't available out-of-the-box, see this GitHub issue, which includes a few comments from Damien Edwards himself:

We purposefully didn't add ViewBag because I wanted to discourage its use.

...

ViewBag uses dynamic which in our testing introduces a measurable performance impact on the processing of pages or views that use it. As such, I'd rather it not be available by default.

The solution is to either use an explicit property (as you're doing for ReturnUrl) or just use ViewData (as you're doing for duplicateEmail).

0
Alaaeddine HFIDHI On

try to replace the viewBag with a viewData :

ViewData["pom"] = 100; 
ViewData["duplicateEmail"] = "Email is already taken";
return Page();

<div class="row">
    <div class="col-md-4">
        <form asp-route-returnUrl="@Model.ReturnUrl" method="post">
            <h4>Create a new account.</h4>
            <h4>@ViewData["duplicateEmail"] error: @ViewData["pom"]</h4>
            <hr />

ViewBag was intentionally left out in razor pages.