简体   繁体   中英

How to redirect to a post action from a get action mvc

I have the following Get action:


        [HttpGet]
        [AllowAnonymous, OnlyAnonymous]
        public ActionResult VerifyVoucherCode()
        {
            var model = new VerifyVoucherCodeModel();

            model.VoucherCode = Request.GetFirstQueryValue("token", "voucherCode");

            if (!string.IsNullOrEmpty(model.VoucherCode))
            {
                 // prepopulates the code for the user already in a form 
            }

            return View(model);
        }

And a POST action for when the user submits the form:

 [HttpPost, AjaxOnly]
        [AllowAnonymous, OnlyAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult VerifyVoucherCode(VerifyVoucherCode model)
        {
            return ExecuteAction(() =>
            {
                // do something 
            });
        }

I want to change the logic so that if the voucher code is in the request, the form is submitted automatically for the user without them having to submit the form themselves (ie it takes them straight to that Post action). I've looked at lots of Stack Overflow questions and answers and it seems I cannot redirect to the Post action. I have also tried creating a second Get action which calls the Post action but that does not work either. Does anyone know the correct way to approach this problem?

Thanks

Assuming the model contains a single string for the voucher, you can do something like this:

[HttpGet]
[AllowAnonymous, OnlyAnonymous]
public ActionResult VerifyVoucherCode(string id)
{
    if(string.IsNullOrEmpty(id))
{
    MyModel model1 = new MyModel();
    ...
    return View(model1);
}
    //otherwise process the voucher here
    ...
    return RedirectToAction("SuccessMsg");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM