Create controller for partial view in ASP.NET MVC

后端 未结 6 483
情话喂你
情话喂你 2020-12-07 14:34

How can I create an individual controller and model for a partial view? I want to be able to place this partial view any where on the site so it needs it\'s own controller.

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 15:23

    Why not use Html.RenderAction()?

    Then you could put the following into any controller (even creating a new controller for it):

    [ChildActionOnly]
    public ActionResult MyActionThatGeneratesAPartial(string parameter1)
    {
        var model = repository.GetThingByParameter(parameter1);
        var partialViewModel = new PartialViewModel(model);
        return PartialView(partialViewModel); 
    }
    

    Then you could create a new partial view and have your PartialViewModel be what it inherits from.

    For Razor, the code block in the view would look like this:

    @{ Html.RenderAction("Index", "Home"); }
    

    For the WebFormsViewEngine, it would look like this:

    <% Html.RenderAction("Index", "Home"); %>
    

提交回复
热议问题