how to properly redirect to page in asp.netcore

Viewed 7776

edit:background on project. This was project was created following the concepts from the tutorials here on data access with razor pages https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/?view=aspnetcore-2.2. i did not do views or controllers so I currently do not have any actions i can redirect to. do i need to add a controllers folder?

When I save changes to my edit of the model subcategories, I want to go back to the categories page. Normally, this would be fine with a simple RedirectToPage("/index").

That doesn't work here because my index OnGet uses a string ID to filter through the the subcategories (which feels like I'm probably doing that wrong... but it works). Below is what I currently have and it obviously doesn't work:

Edit - OnPost:

public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    _context.Attach(Subcategory).State = EntityState.Modified;

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!SubcategoryExists(Subcategory.SubcategoryId))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return RedirectToPage("./Index", "?id" , Subcategory.CategoryName);
}

Index - OnGet:

public async Task OnGetAsync(string id)
{
    title = id;

    Subcategory = await _context.Subcategory.ToListAsync();

    foreach (Subcategory item in Subcategory.ToList())
    {
        if (item.CategoryName != id)
        {
           Subcategory.Remove(item);
        }
    }

}

Can anyone tell me how to properly route the OnPost of my edit razor page to the OnGet of my index razor page?

I've tried to do some research on handlers but I couldn't find a good understandable definition of how to do this.

2 Answers

It is a bit hard to see where you have hooked stuff up, as you have only provided the methods.

Given that OnGetAsync(string id) if mapped to /index you could use something like:

return RedirectToAction("Index", new { id = Subcategory.CategoryName.ToString() });

I would also suggest that you call your methods the same as the endpoint. So if OnGetAsync is your index endpoint. Then call it Index.

Hopefully this helps you, or else you need to provide me with more code.

the fix to the problem without building a controller was pretty much what Kristian Barrnet was saying:

   return RedirectToPage("./Index", new { id = Subcategory.CategoryName.ToString() });

however, I should probably add some controllers here anyway to make this a lot more organized

Related