drethedevjs
drethedevjs

Reputation: 484

Redirect to Page with ID in Razor Pages

I'm trying to get my app to redirect to the previous page after it updates the database but I can't seem to figure it out. What's complicating it is that the previous page isn't just a simple page. It's populated with information pulled but a specific row in the database so the URL has

blah blah blah.../ProjectDetails?id=(the ID number)

I've tried using the Redirect Methods but they aren't as straight forward as I'd hoped. Can someone help me figure out how to go back to the previous page?

View

<form method="post">
  <select class="custom-select mb-4 col-6" name="Assignee">
       <option>John</option>
       <option>Jane</option>
       <option>Jim</option>
       <option>Juju</option>
  </select>
  <br>
  <button type="submit" class="btn btn-info">Save</button>
  <a class="btn btn-danger" asp-page="./Teamlead">Cancel</a>
</form>

Code Behind

public async Task<IActionResult> OnPostAsync(int id)
{
   Submission = _SubmissionContext.Submissions
                                .Where(s => s.ID == id).First();
   Submission.AssignedTo = Assignee;
   await _SubmissionContext.SaveChangesAsync();
    
   return RedirectToRoute("./ProjectDetails"); //PROBLEM HERE
}

Upvotes: 5

Views: 23642

Answers (2)

Andrew
Andrew

Reputation: 258

You should try decorating your razor page view at the top with your route attributes like so:

@page "{id}"

The following link below should help example more about routing parameters:

See mikesdotnetting.com - routing-in-razor-pages

Adding constraints

From learnrazorpages.com - Razor Pages Routing you can also add this to the razor page

@page "{id:int}"

Upvotes: 4

Brad Patton
Brad Patton

Reputation: 4205

You need to pass the id to the redirected page. You can use an anonymous type to do that like:

public async Task<IActionResult> OnPostAsync(int id)
{
   Submission = _SubmissionContext.Submissions
                            .Where(s => s.ID == id).First();
   Submission.AssignedTo = Assignee;
   await _SubmissionContext.SaveChangesAsync();

   return RedirectToRoute("./ProjectDetails", new { id = Submission.ID });
}

Upvotes: 16

Related Questions