简体   繁体   中英

HTTP Post does not return the view in ASP.NET MVC Core 2

What happens is when i click a link it goes to http get RsvpForm method and return the view. In the view it return has the form. But after i submit the form it does not return back to the reload the view. I confirm this by the value i key in the text box does not cleared. I know how to clear the textbox but my concern was i want it to reload the same view when i click on the submit button which is a post method in the form. Below is my code.

    [HttpGet]
    public ViewResult RsvpForm()
    {
        return View();
    }

    [HttpPost]
    public ViewResult RsvpForm(GuestResponse guestResponse)
    {

        return View();
    }

When the modelbinder binds request data to a model, it also composes ModelState from that data. ModelState determines what is displayed in bound form fields, so that's why your field has the posted data in it.

It works this way because if there's an error in the form (it fails server-side validation), you'd normally return the view again so the user can fix their mistake(s). Additionally, you'd want the posted data to be in the appropriate fields, at that point, so the user can just edit what was wrong, instead of having to start completely over filling out the form. Since you're returning the view on "success", this same behavior is occurring, even though there were no validation errors.

Long and short, you should be following the PRG (Post-Redirect-Get) pattern. On post, you return the view only on error. On success, you redirect. If you want the user to see the same form again on success, then simply redirect to the same page. The act of redirecting causes a new GET request, clearing out ModelState from the previous POST.

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