Post Redirect Get in ASP.NET MVC And Validation With Restful URLs

前端 未结 3 817
猫巷女王i
猫巷女王i 2020-12-08 16:10

I have a restful URL for the action of editing a page. This is implemented on the controller as an Edit method, which accepts GET requests and an Edit method that accepts PO

3条回答
  •  一生所求
    2020-12-08 17:01

    PRG is the right thing to do.

    You do a POST to the action and if modelstate is invalid, you just 'export' your modelstate data into a variable and redirect to the get action.

    This has the benefit as opposed to the accepted answer that you don't need to rewrite code on the [Post] action to recreate the view.

    on the get action you load the ModelState exported from the post one.

    TempData is an excellent place to do this stuff, code will be something like this:

    [HttpGet]
    public ActionResult Edit(int id) {
        // import model state from tempdata
        ...
    }
    
    [HttpPost]
    public ActionResult Edit(EditModel model) {
        // if modelstate is invalid
        // save modelstate in tempdata
        // redirect to Edit/{id}
        // else 
        ...
        RedirectToAction("List")
    }
    

    this can be automated using AttributeFilters, there an excellent post create by @ben-foster here:

    Automatic Validation of Modelstate

提交回复
热议问题