You do not need code files. Create a model for PartialView (ViewUserControl) and bind it to your control.
The point of MVC is to keep control away from a view that should be dumb ... or at least non-smart. Your controller must click the object onto the Model object, which already has everything that View needs.
Declare Model
public class MyModel { public IList<MyPartialView> Controls { get; set; } } public class MyPartialView { public string Field1 { get; set; } public string Field2 { get; set; } }
Create your action in your controller by passing a MyModel object
public ActionResult Index() { MyModel model = new MyModel(); model.Controls.Add(new MyPartialView() { Field1 = "a", Field2 = "b" }; model.Controls.Add(new MyPartialView() { Field1 = "x", Field2 = "y" }; model.Controls.Add(new MyPartialView() { Field1 = "m", Field2 = "n" }; return View(model); }
Create your view by strictly typing MyModel
<%@ Page Language="C#" Inherits="ViewPage<MyModel>" %> <% foreach(MyOtherPartialView partial in Model.Controls) { %> <%=Html.RenderPartial("MyPartialView", partial) %> <% } %>
Create your partial view , gated on MyPartialView
<%@ Control Language="C#" Inherits="ViewUserControl<MyPartialView>" %> <div> <%=Model.Field1 %> - <%=Model.Field2 %> </div>
source share