开发者

How to create an MVC UserControl

开发者 https://www.devze.com 2023-02-09 19:57 出处:网络
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 lik

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 开发者_StackOverflowcodefile. 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).


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消