4

I am trying to create a user control in an ASP.NET MVC project. I basically have some formatted data that I want to put inside a repeater. In standard ASP.NET, I would populate the control something like this:

 <asp:Repeater ID="MyRepeater" runat="server" 
               DataSourceID="SQLDataSource" DataMember="DefaultView">
     <ItemTemplate>                             
          <uc1:Control ID = "MyControl" runat="server" 
                       Field1='<%#Eval("[\"Field1\"]") %>' Field2='<%#Eval("[\"Field2\"]") %>' />                            
     </ItemTemplate>
 </asp:Repeater>

And the control would have corresponding properties in the codefile. However, in MVC, I don’t get a codefile as standard. I found this question that describes how to add one, but then wondered if there is a better way of doing this in MVC (I couldn’t find any decent articles that said the recommended way).

Community
  • 1
  • 1
Paul Michaels
  • 16,185
  • 43
  • 146
  • 269

1 Answers1

3

You don't need code-behind files. Create a Model for your PartialView (ViewUserControl) and bind that to your control.

The point of MVC is to keep the control away from the View, which should be dumb... or at least not-smart. Your Controller should push an object to the containing a Model object that already has everything the View needs.

Declare your 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 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 strongly typed to MyModel

<%@ Page Language="C#" Inherits="ViewPage<MyModel>" %>

<% foreach(MyOtherPartialView partial in Model.Controls) { %>
<%=Html.RenderPartial("MyPartialView", partial) %>
<% } %>

Create your Partial View stronly typed to MyPartialView

<%@ Control Language="C#" Inherits="ViewUserControl<MyPartialView>" %>

<div>
    <%=Model.Field1 %> - <%=Model.Field2 %>
</div>
hunter
  • 62,308
  • 19
  • 113
  • 113
  • Are you saying that the data access should be in the Controller? I was under the impression that this should be in the Model. – Paul Michaels Feb 22 '11 at 13:02
  • 1
    The controller should push data to the model and pull data from the model. The model should be dumb. Your controller should not handle data access directly if you're doing n-tier development. The controller could talk to a business layer, which requests from the data access layer, which hands back raw data, which the business layer transforms into usable objects for the controller. – hunter Feb 22 '11 at 14:57