Reputation: 12996
I'm trying to add a form post that's generated through Javascript on a page.
I started out with the following route defined:
routes.MapRoute(name: "ItemLinks", url: "ItemRequestController/DoItemRequest", defaults: new { controller = "ItemRequest", action = "DoItemRequest" });
But I wasn't able to get the form values from the request object in my controller action method.
So I defined the following route:
routes.IgnoreRoute("ItemRequestController/{*pathInfo}");
The form is defined as:
@using (Html.BeginForm("DoItemRequest", "ItemRequestController", FormMethod.Post))
{
@Html.AntiForgeryToken()
<input type="hidden" name="hid_ItemID" value="" />
<input type="hidden" name="hid_PositionOnPage" value="" />
In the js function, I define the values (based on the click) of the hidden fields, then do:
document.forms[0].submit();
The problem is that I'm now getting the error...
The HTTP verb POST used to access path '/ItemRequestController/DoItemRequest' is not allowed.
How can I get around this, and read the form POST values in my controller action method?
-- UPDATE --
Can't believe I forgot to add this...
I'm sure there's a more elegant way of pulling the request var's... open to suggestions.
Controller method:
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult DoItemRequest()
{
int itemListID = 0;
int pagePositionNumber = 0;
int.TryParse(Request["itemListID"], out itemListID);
int.TryParse(Request["pagePositionNumber"], out pagePositionNumber);
Upvotes: 1
Views: 1689
Reputation: 17485
First of all remove your ignoreroute part from Global.asax
Now come to issue. MVC is convention based ( default implementation ) Use this .
@using (Html.BeginForm("DoItemRequest", "ItemRequest", FormMethod.Post))
{
@Html.AntiForgeryToken()
<input type="hidden" name="hid_ItemID" value="" />
<input type="hidden" name="hid_PositionOnPage" value="" />
you have to specify Controller name only which ItemRequest not ItemRequestController. You class is ItemRequestController but postfix Controller by default Add by MVC. So when you use ItemRequestController in BeginForm it will search for ItemRequestControllerController class which not found and exception is thrown.
This will solve your issue.
Upvotes: 0
Reputation: 14944
Make sure your controller method is defind as HttpPost
[HttpPost] // Or [AcceptVerbs(HttpVerbs.Post)]
public ActionMethod DoItemRequest(FormCollection data)
{
}
Upvotes: 2