Using Html.BeginForm to post to the current controller

后端 未结 3 1639
温柔的废话
温柔的废话 2021-01-12 10:37

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 act

相关标签:
3条回答
  • 2021-01-12 11:09

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

    Html.BeginForm("ActOnChoosenPerson", ViewContext.RouteData.
        GetRequiredString("controller"))
    
    0 讨论(0)
  • 2021-01-12 11:13

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

    0 讨论(0)
  • 2021-01-12 11:29

    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.

    0 讨论(0)
提交回复
热议问题