8

I have a partial that is used in several views. The partial contains forms. The action when a form is submited is allways the same, but the controller thats contains the action depends on the view.

Lets say I have Controllers that each have an action ActOnChoosenPerson:

FireStaffController

HireStaffController

I have a partial

PersonList.ascx

The forms are rendered as

Html.BeginForm("FireStaffController" , "ActOnChoosenPerson") or

Html.BeginForm("HireStaffController" , "ActOnChoosenPerson")

What is a good way to get rid of the controller parameter? Right now I pass the name of the current controller into the model and use

Html.BeginForm(Model.CurrentController , "ActOnChoosenPerson")

but that is a bit awkward.

Community
  • 1
  • 1
Mathias F
  • 15,906
  • 22
  • 89
  • 159

3 Answers3

8

This code will always give your current controller

<%=( Url.RequestContext.RouteData.GetRequiredString("Controller")) %>

Obviously you can use it without the <%= like this

Html.BeginForm(
  Url.RequestContext.RouteData.GetRequiredString("Controller")) , 
  "ActOnChoosenPerson") 

It looks more clunky but your model should not need to know what controller is calling it.

Mark Dickinson
  • 6,573
  • 4
  • 29
  • 41
7

ViewContext's RouteData property contains names of current controller and action. You could use them like this:

Html.BeginForm("ActOnChoosenPerson", ViewContext.RouteData.
    GetRequiredString("controller"))
Alexander Prokofyev
  • 33,874
  • 33
  • 95
  • 118
0

The easiest way to do this would be to simply call BeginForm() with no parameters.

user1751825
  • 4,029
  • 1
  • 28
  • 58