.NET MVC Call method on different controller

前端 未结 7 1417
Happy的楠姐
Happy的楠姐 2020-11-30 06:26

Can anybody tell me how to call a method on a different controller from within an action method? I don\'t want to redirect. I want to call a method on a different controller

7条回答
  •  误落风尘
    2020-11-30 07:08

    You can achieve this via the Action method of HtmlHelper.

    In a view, you would do it like this:

    @Html.Action("OtherAction")
    

    However it's not straightforward to obtain an instance of HtmlHelper in an action method (by design). In fact it's such a horrible hack that I am reluctant to even post it...

    var htmlHelper = new HtmlHelper(new ViewContext(
                                          ControllerContext, 
                                          new WebFormView(ControllerContext, "HACK"),
                                          new ViewDataDictionary(),
                                          new TempDataDictionary(),
                                          new StringWriter()),
                                    new ViewPage());
    
    var otherViewHtml = htmlHelper.Action("ActionName", "ControllerName");
    

    This works on MVC 3. You might need to remove the StringWriter arg from the ViewContext constructor for MVC 2, IIRC.

提交回复
热议问题