ASP.NET MVC - redirect after form submit

14,469

Not sure if this issue was with an earlier version of MVC, but I have often forgotten that the [HttpPost] label may be placed above an ActionResult in the controller and not just above a JsonResult.

So the simplest MVC-style answer would be just use Html.BeginForm and post to the ActionResult (with the [HttpPost] attribute), wherein you execute your logic, then call RedirectToAction at end after you have handled the post controller side.

This seems far easier than all the client-side fiddles, e.g. window.location.href = '' etc...

Share:
14,469
user3544117
Author by

user3544117

Updated on June 04, 2022

Comments

  • user3544117
    user3544117 about 2 years

    I have a ASP.NET MVC website and a "Configuration" view with a form.

    When I submit the form, I would like to do some stuff and then Redirect to my "Initialization" ViewResult... How to do it ?

    My form :

    @using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "Config" }))
    {
         // Some fields
    
         <input type="submit" value="Save" />
    
    }
    

    then, the "Save" action :

    [HttpPost]
    [ValidateAntiForgeryToken()]
    public async Task<RedirectToRouteResult> Save(Config websiteConfiguration)
        {
            // Do some stuff
    
            bool ok = await myMethod();
    
            if(ok)
            {
                return RedirectToAction("Initialization");
            }
    
        }
    

    I tried other possibilities but I don't manage to get it work...

    Up, I still have the problem...

    • Mukesh Modhvadiya
      Mukesh Modhvadiya about 10 years
      what error or problem are you getting with above code?
    • user3544117
      user3544117 about 10 years
      Sorry, it doesn't do the redirection, it reload the "Configuration" View instead
    • Mukesh Modhvadiya
      Mukesh Modhvadiya about 10 years
      if your "myMethod()" returns false then it will realod "ConfigurationView" and if returns true then only redirection occures, I think
    • user3544117
      user3544117 about 10 years
      But my myMethod() return true, and the redirection doesn't work...
    • Mukesh Modhvadiya
      Mukesh Modhvadiya about 10 years
      try changing your code as I have shown in answer, if it is working or not
  • Mukesh Modhvadiya
    Mukesh Modhvadiya about 10 years
    @Amit, this will do redirection, but it is not ideal, if you are posting data to controller, then you should do redirection from controller side.
  • Amit
    Amit about 10 years
    @Mark its not necessary. we can post data to controller by View easily
  • Mukesh Modhvadiya
    Mukesh Modhvadiya about 10 years
    @Amit, my intension was not that this is wrong, I was just talking what is ideal. This place is just for sharing knowledge. Down voting doesnt make sense. No worries.