Create controller for partial view in ASP.NET MVC

后端 未结 6 484
情话喂你
情话喂你 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:11

    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, ). For more details see ASP.NET MVC partial views: input name prefixes

提交回复
热议问题