Html.RenderAction uses Post instead of Get

2020-03-24 06:33发布

问题:

I have a simple form on my page. When submitted, it checks if ModelState.IsValid and returns the View with the same model if it's not valid.

On the same page, I'm rendering an action that contains another form like so:

Html.RenderAction("AccountNote", new { id = Model.ID });

Everything works fine until I submit the form on my page and the validation fails. When it shows the page again, the AccountNote action's Post event fires when I'd expect the Get event to fire. I guess it makes sense why it's happening since it's the post that action that's rendering the view, but I want the Get event to fire instead.

public ActionResult AccountNote(int id)
{
    //code goes here...

     return PartialView(model);
}

[HttpPost]
public ActionResult AccountNote(AccountNoteViewModel model)
{
    //code goes here...

    return PartialView(model);
}

Am I doing something incorrect? Or is there some trickery I have to do to make this work? I would expect the Html.RenderAction to always assume GET instead of POST.

回答1:

One solution would be to have only one AccountNote() action method. Then it will be called regardless of GET or POST. You might have to modify your logic a bit if you were using POST version of AccountNote().

And you can decorate it with [ChildActionOnly] attribute.



回答2:

Since I know, there is not any solution for this problem out of the box. RenderAction and Action methods, consider the current request for deciding on to use which verb. But you can rename them. For example rename the one that is restricted to HttpPost to AddAccountNote and leave the other one with the current name and without specifying its verb.



回答3:

Would RenderPartial be an option for you?

More discussion on this topic can be found here: RenderAction calls wrong action method