20

I do this very often:

<div id='Product'>
@Html.Action("Create", "Product")
</div>

it's convenient because I can delegate the painting of a product creation form to another controller action for embedding in places. However, I'm having issues in that the method will sometimes (I haven't figured out under what conditions) call the [HttpPost] of my controller action, which of course fails.

Is there a way to force @Html.Action() to call the GET version?

ekkis
  • 9,804
  • 13
  • 55
  • 105

4 Answers4

20

The way Html.Action works is that if the current request for the page is a post method then it will search for the method with the name HttpPost.

So what's happening is that you're POSTing the current page and the action likewise assumes all actions that should execute must be a POST too.

There's no way I know of to force it to switch to a different method like that.

Buildstarted
  • 26,529
  • 10
  • 84
  • 95
  • 7
    yes, I did figure that out. that is a terrible assumption on their part. What I ended up doing is renaming the actions so that there's no ambiguity – ekkis Jul 02 '11 at 17:22
  • That's probably the best solution. Glad to be of help. – Buildstarted Jul 02 '11 at 17:45
5

Try adding the AcceptVerbs attribute to your action:

[AcceptVerbs(HttpVerbs.Get|HttpVerbs.Post)]
public ActionResult Create()
{
    //Your code
}

This will work for both GET and POST requests.

Jørn Schou-Rode
  • 37,718
  • 15
  • 88
  • 122
Champ
  • 118
  • 2
  • 6
  • hmm... yes but that would force me to code both behaviours into the same method... which means I would need a way to tell within the method whether a Post or Get was performed... how would this be done? – ekkis Jul 07 '14 at 02:25
-1

I also got into a similar problem and there indeed is a solution. Just Check whether Request is get or POST in View using IsPost Property and VOILA....

@if(!IsPost)    
{    
    HTML.Action("ActionName")    
}

Regards to whoever got in similar problem...

ekkis
  • 9,804
  • 13
  • 55
  • 105
Faizal Shap
  • 1,680
  • 1
  • 11
  • 26
-2

I just encountered this issue, which was hard to identify. I ended up using Html.RenderPartial instead, like this:

<div id='Product'>
@{Html.RenderPartial("_CreatePartial", new Product());}
</div>
wooters
  • 829
  • 6
  • 24