Create controller for partial view in ASP.NET MVC

asp.netasp.net MvcPartial Views

asp.net Problem Overview


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. I am current rendering the partial as so

@Html.Partial("_Testimonials")

asp.net Solutions


Solution 1 - asp.net

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"); %>

Solution 2 - asp.net

If it were me, I would simply create a new Controller with a Single Action and then use RenderAction in place of Partial:

// Assuming the controller is named NewController
@{Html.RenderAction("ActionName", 
                     "New", 
                      new { routeValueOne = "SomeValue" });
}

Solution 3 - asp.net

It does not need its own controller. You can use

@Html.Partial("../ControllerName/_Testimonials.cshtml")

This allows you to render the partial from any page. Just make sure the relative path is correct.

Solution 4 - asp.net

The most important thing is, the action created must return partial view, see below.

public ActionResult _YourPartialViewSection()
{
    return PartialView();
}

Solution 5 - asp.net

You don't need a controller and when using .Net 5 (MVC 6) you can render the partial view async

@await Html.PartialAsync("_LoginPartial")

or

@{await Html.RenderPartialAsync("PartialName");}

or if you are using .net core 2.1 > you can just use:

<partial name="Shared/_ProductPartial.cshtml"
         for="Product" />

Solution 6 - asp.net

Html.Action is a poorly designed technology. Because in your page Controller you can't receive the results of computation in your Partial Controller. Data flow is only Page Controller => Partial Controller.

To be closer to WebForm UserControl (*.ascx) you need to:

  1. Create a page Model and a Partial Model

  2. Place your Partial Model as a property in your page Model

  3. In page's View use Html.EditorFor(m => m.MyPartialModel)

  4. Create an appropriate Partial View

  5. Create a class very similar to that Child Action Controller described here in answers many times. But it will be just a class (inherited from Object rather than from Controller). Let's name it as MyControllerPartial. MyControllerPartial will know only about Partial Model.

  6. Use your MyControllerPartial in your page controller. Pass model.MyPartialModel to MyControllerPartial

  7. Take care about proper prefix in your MyControllerPartial. Fox example: ModelState.AddError("MyPartialModel." + "SomeFieldName", "Error")

  8. In MyControllerPartial you can make validation and implement other logics related to this Partial Model

In this situation you can use it like:

public class MyController : Controller
{
    ....
    public MyController()
    {
    MyChildController = new MyControllerPartial(this.ViewData);
    }

    [HttpPost]
    public ActionResult Index(MyPageViewModel model)
    {
    ...
    int childResult = MyChildController.ProcessSomething(model.MyPartialModel);
    ...
    }
}

P.S. In step 3 you can use Html.Partial("PartialViewName", Model.MyPartialModel, <clone_ViewData_with_prefix_MyPartialModel>). For more details see https://stackoverflow.com/questions/1488890/asp-net-mvc-partial-views-input-name-prefixes#answer-36495608

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbrenjtView Question on Stackoverflow
Solution 1 - asp.netGeorge StockerView Answer on Stackoverflow
Solution 2 - asp.netJustin NiessnerView Answer on Stackoverflow
Solution 3 - asp.netSlick86View Answer on Stackoverflow
Solution 4 - asp.netWen ChenView Answer on Stackoverflow
Solution 5 - asp.netGoldenAgeView Answer on Stackoverflow
Solution 6 - asp.netYury ShpakovView Answer on Stackoverflow