Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

MVC - Using Html.BeginForm() with the correct route

Vote:
 

Lets say I have this controller,

public class SomePageController : PageControllerBase<SomePage>
  {
    [HttpGet]
    public ActionResult Index(SomePage currentPage)
    {
      return View(model);
    }

    [HttpPost]
    public ActionResult PostData(PostModel model)
    {
      return RedirectToAction("Index");
    }
  }

 

The url to this page could be localhost:37000/sv/super-page

And in the view I create a form using @using Html.BeginForm("PostData", "SomePage", null, FormMethod.Post) {}

I would expect that to work as that's how MVC usually works but with EPi it doesn't.

The form is posting to /sv/super-page/postdata which doesn't correspond to the SomePageController.

When posting forms in EPiServer MVC, how to I post them to the correct controller and action method?

 

#77842
Nov 27, 2013 10:45
Vote:
 

Can you have your form handle method be named the same as your default action? It would be much easier for Mvc to route through:

 

@using (Html.BeginForm(null, null, new { language = ContentLanguage.PreferredCulture.Name }, FormMethod.Post) { ... }

    

public class SomePageController : PageControllerBase<SomePage>
  {
    [HttpGet]
    public ActionResult Index(SomePage currentPage)
    {
      return View(model);
    }

    [HttpPost]
    public ActionResult Index(PostModel model)
    {
      return RedirectToAction("Index");
    }
  }

    

#77844
Nov 27, 2013 10:58
Vote:
 

That doesn't work. It returns 404 just like my example above.

#77845
Nov 27, 2013 11:07
Vote:
 

/sv/super-page goes to SomePageController's index action method right? If that's the case then /sv/super-page/postdata is correct. What does your http body (of the request) look like?

Frederik

#77850
Nov 27, 2013 11:33
Vote:
 

Yes that's true Frederik.

I see what's going wrong now, from /sv/super-page it posts to /super-page/postdata. The /sv/ part is missing and therefore it returns 404.

How do I include that?

#77856
Edited, Nov 27, 2013 11:49
Vote:
 

Like in Valdis' example, with new { language = ContentLanguage.PreferredCulture.Name } (this is the additional route parameter).

Frederik

#77859
Nov 27, 2013 11:53
Vote:
 

Thanks for pointing that out, I missed that.

Thanks for your help Valdis and Frederik!

#77860
Nov 27, 2013 11:55
This thread is locked and should be used for reference only. Please use the Episerver CMS 7 and earlier versions forum to open new discussions.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.