"Resource not found" using HttpPost in MVC

I see that my problem is a common mistake and tried many times to answer this problem, but it still does not work for me. So, to start forming the beginning, I have a partial form in an MVC project that uses the Html.BeginForm helper:

<%using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new{@class = "form-class"})) 

"MyAction" and "MyController" are not actual names, but they are allowed, as confirmed names confirm. My action in my controller:

 [HttpPost] public ActionResult MyAction(int id, FormCollection form) { EditedData dt = new EditedData(); // does some db submits and returns edited data return View(dt); } 

So the common problem seems to be that using [HttpPost] returns a "Resource not found" error. I debugged with [HttpPost] a comment that removes MyAction so that it does not route (?). global.asax has not been changed:

 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } 

As I said, I tried other answers in other posts that seem to work on the poster, but I still have a problem. What am I missing?

PS In View Source, I see a form tag read:

 <form method="post" action="690" id="form1"> 

when the action should point to MyAction. How to install Html.BeginForm to point to "MyAction"?

+4
source share
1 answer

The problem is that the action id parameter is int (value type), it cannot be passed as a null reference. Thus, you need to explicitly specify the value 0 in the BeginForm call (in the view) or make it valid.

Basically, the routing mechanism cannot decide your action and the controller based on the data you gave it (the name of the action and the name of the controller) + route mappings.

Example (in case you decide to save the parameter as int ):

 <%using (Html.BeginForm("MyAction", "MyController", new { id = 0 }, FormMethod.Post, new { @class = "form-class" })) 

This overload will match the signature you specified in the controller. When you edit, just replace 0 with any property of the model; eg:

 <% using (Html.BeginForm("MyAction", "MyController", new { id=Model.ID }, FormMethod.Post, new{ @class = "form-class"})) %> 
+4
source

Source: https://habr.com/ru/post/1482995/


All Articles