Using Html.BeginForm to send to the current controller

I have a partial one that is used in several views. Partial contains forms. The action when submitting the form is always the same, but the controller that contains the action depends on the view.

Suppose I have controllers, each of which has an ActOnChoosenPerson action:

Firestaffcontroller

Hirestaffcontroller

I have a partial

PersonList.ascx

Forms are displayed as

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

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

What is a good way to get rid of a controller parameter? Right now I am passing the name of the current controller to the model and using

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

but it is a little uncomfortable.

+6
asp.net-mvc
Jun 23 '09 at 9:08
source share
3 answers

This code will always be provided by the current controller.

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

Obviously you can use it without <% = like this

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

It looks more awkward, but your model does not need to know what the controller is calling.

+8
Jun 23 '09 at 9:30 a.m.
source share

The ViewContext RouteData property contains the names of the current controller and action. You can use them as follows:

 Html.BeginForm("ActOnChoosenPerson", ViewContext.RouteData. GetRequiredString("controller")) 
+6
Jun 23 '09 at 9:29
source share

The easiest way to do this is to simply call BeginForm () without parameters.

0
Jun 11 '16 at 8:56
source share



All Articles