Friday, June 6, 2014

ASP.NET MVC ActionResult with [HttpPost, HttpPut] filter not executing

Given the ActionResult method and View that executes the controller.
ActionResult:
Code:
       [HttpPost, HttpPut] 
       public ActionResult Update(EditModel input)
        {
            if (ModelState.IsValid)
            {
                var person = Database.People.Find(input.Id);
                input.ToPerson(person);

                Database.SaveChanges();

                return RedirectToAction("Edit", new { id = person.Id });
            }

            return View("Edit", input);
        }

View:
 @model PagedListTableMvcDemo.Models.EditModel  
 @{  
   ViewBag.Title = "Edit";  
 }  
 <h2>Update</h2>  
 @using (Html.BeginForm("Update", "People")) {  
   @Html.Partial("_Person")  
 }  
When the user clicks the submit button rendered by the BeginForm helper, the browser shows an error URL not found or The view does not navigate to the Action with the corresponding Controller supplied in the BeginForm's parameters. The solution is to replace %5BHttpPost, HttpPut%5D with AcceptVerbs attribute.
Code:
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)]
        public ActionResult Update(EditModel input)
        {
            if (ModelState.IsValid)
            {
                var person = Database.People.Find(input.Id);
                input.ToPerson(person);

                Database.SaveChanges();

                return RedirectToAction("Edit", new { id = person.Id });
            }

            return View("Edit", input);
        }

0 comments:

Post a Comment