Can’t redirect to another action method after form submission

I want to redirect to an action that says Order is successful, but when the form is submitted, it redirects to the same action /Checkout with error: This page isn't working. This is understandble since the query strings are not present, but this doesn’t matter to me. I want
it to redirect to /OrderComplete instead. The debugger confirmed ModelState is valid and RedirectToAction is hit every time.

These are the get and post action methods.

public async Task<IActionResult> Checkout(string vendorId, int skillId)
{
    var skill = await _skillRepository.GetSkillById(skillId);
    OrderViewModel OrderView = new OrderViewModel
    {
        ApplicationUserId = vendorId,
        ServiceType = skill.SkillType
    };
    return View(OrderView);
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Checkout(OrderViewModel orderViewModel)
{
    if (ModelState.IsValid)
    {
        _orderRepository.CreateOrder(orderViewModel);
        return RedirectToAction("OrderComplete");
    }
    return View(orderViewModel);
}

This is the form action in view.

<form asp-action="Checkout" method="post">

Note: ApplicationUserId and ServiceType are hidden fields that
are filled before posting the form.

Update

After commenting out this line _orderRepository.CreateOrder(orderViewModel);, it redirected successfully. So, the problem seems to be coming from this method CreateOrder.

public class OrderRepository : IOrderRepository
{
    private readonly QuickServiceDbContext _context;
    private readonly IMapper _mapper;
    public OrderRepository(QuickServiceDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }
    public void CreateOrder(OrderViewModel orderViewModel)
    {
        Order order = _mapper.Map<Order>(orderViewModel);
        _context.Orders.Add(order);
        //_context.Users
        _context.SaveChangesAsync();
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Changing _context.SaveChangesAsync() to:

_context.SaveChanges();

fixed the issue. I don’t understand why this is yet, but I should never have spent so much time on an issue so trivial. Any insight into why SaveChangesAsync() was preventing a redirection would be appreciated.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x