How To Insert Partial views Dynamically in Asp.Net MVC

后端 未结 1 1022
长情又很酷
长情又很酷 2020-12-30 15:42

I am migrating a Webforms site to MVC. In my webforms site I have pages that utilise various combinations of User Controls, then chunks of html then Labels, Textboxes etc.

相关标签:
1条回答
  • 2020-12-30 16:14

    If I understood you correctly this should solve your problem

    Just create a new class derived from PartialViewResult which accepts multiple view names to render them. And to make it a little more usable create a new extension method for the controller to call your customized ViewResult.

    That worked for me. You can use it so simply:

    public ActionResult Index()
    {
        return this.ArrayView(new string[] { "ViewA", "ViewB" });
    }
    

    To make it work ArrayViewResult class should be:

    public class ArrayViewResult : PartialViewResult
    {
        public IEnumerable<string> Views;
    
        protected override ViewEngineResult FindView(ControllerContext context)
        {
            return base.FindView(context);
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (!Views.Any())
                throw new Exception("no view...");
    
    
            TextWriter writer = context.HttpContext.Response.Output;
    
            foreach(var view in Views)
            {
                this.ViewName = view;
                ViewEngineResult result = FindView(context);
    
                ViewContext viewContext = new ViewContext(context, result.View, ViewData, TempData, writer);
                result.View.Render(viewContext, writer);
    
                result.ViewEngine.ReleaseView(context, result.View);
            }
        }
    }
    

    Extension method:

    namespace System.Web.Mvc
    {
        public static class ArrayViewResultExtension
        {
            public static ArrayViewResult ArrayView(this Controller controller, string[] views)
            {
                return ArrayView(controller, views, null);
            }
            public static ArrayViewResult ArrayView(this Controller controller, string[] views, object model)
            {
                if (model != null)
                {
                    controller.ViewData.Model = model;
                }
    
                return new ArrayViewResult
                {
                    ViewName = "",
                    ViewData = controller.ViewData,
                    TempData = controller.TempData,
                    ViewEngineCollection = controller.ViewEngineCollection,
                    Views = views
                };
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题