I cannot work out why BeginUmbracoForm is generating a form that posts back to the wrong controller. I figure this is due to data within the hidden upfrt field but I cannot find a solution or really understand why it's happening.
- MainFormController (a RenderController) returns a view MyMainView
- MyMainView loads MyViewComponent
- MyViewComponent returns a view MyFormView
- MyFormView uses
Html.BeginUmbracoForm- I want this to post back to SecondaryFormController (a SurfaceController)
The form always posts back to MainFormController, why?
What’s happening that triggers Umbraco to route to MainFormController rather than SecondaryFormController?
Here’s trimmed down version of the code:
MainFormController:
public class MainFormController: RenderController {
public MainFormController() {}
public override IActionResult Index() {
var viewModel = new MainFormControllerViewModel() {
...
}
return CurrentTemplate(viewModel); // MyMainView
}
}
MyMainView for MainFormController.Index:
@inherits UmbracoViewPage <MyApp.MainFormControllerViewModel>
@(await Component.InvokeAsync < MyApp.MyViewComponent > ())
MyViewComponent:
public class MyViewComponent: ViewComponent {
public MyViewComponent() {
}
public async Task <IViewComponentResult> InvokeAsync() {
return View(new MyViewComponentViewModel())
}
}
The view/template for MyViewComponent:
@model MyApp.MyViewComponentViewModel
@using(Html.BeginUmbracoForm < MyApp.SecondaryFormController > (
nameof(MyApp.SecondaryFormController.MyAction),
"Update",
null,
) {
<button type ="submit">Update</button>
}
SecondaryFormController.MyAction:
public class SecondaryFormController: SurfaceController {
public SecondaryFormController() {}
[HttpPost]
[ValidateAntiForgeryToken]
[UnsupportedOSPlatform("browser")]
public async Task <IActionResult> MyAction(MyViewComponentViewModel model) {
// do something
return CurrentUmbracoPage();
}
}
If I drop UmbracoBeginForm and use a normal form, it will post to SecondaryFormController.MyAction but I lose the Umbraco context which is no good.
If I drop the view component, and render the form on first view (MyMainView) the behaviour remains the same.
What am I missing here?
1 Answer 1
Detail matters.
In an attempt to keep this brief, I glossed over the fact MyFormView contains another view component. This is fine, but it happens to be a form, and it's rendering before `@using(Html.BeginUmbracoForm <MyApp.SecondaryFormController ...` is closed.
This results in a form within a form which is invalid HTML and just breaks things.
Refactoring so the form isn't rendered within another form fixes the issue.
Comments
Explore related questions
See similar questions with these tags.