Viewbag resetting when returning page on Razor Page

Asked

Viewed 15 times

0

On the Onget of the page I load the Viewbag so:

public IActionResult OnGet()
    {
        ViewData["SGP_GRP_IdGrupoProduto"] = new SelectList(grupoProdutoService.GetAll(), "GRP_Codigo", "GRP_Descricao");
        return Page();
    }

When performing the POST on the page and validating the template, if the template is invalid it returns the page but with the empty viewbag (null)

public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
            return Page();

        subGrupoProdutoService.Create(SubGrupoProduto);

        return RedirectToPage("../View/SubGrupo");
    }

What can be done so that when performing the Return page() the viewbag data still remain on the page?

1 answer

0

Viewbag, Viewdata does not have this purpose, they are for data transfer from the inside out only and are discarded along with your page at the time you make the post.

In your case, what you can do is re-assign the data to your Viewdata.

public IActionResult OnPost()
{
    if (!ModelState.IsValid)
    {
        ViewData["SGP_GRP_IdGrupoProduto"] = new SelectList(grupoProdutoService.GetAll(), "GRP_Codigo", "GRP_Descricao");
        return Page();
    }

    subGrupoProdutoService.Create(SubGrupoProduto);

    return RedirectToPage("../View/SubGrupo");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.