How to create an MVC UserControl

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

<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 will have the corresponding properties in the code file. However, in MVC, I do not get the code as standard. I found this question that describes how to add it, but then wondered if there is a better way to do this in MVC (I could not find any decent articles that said the recommended way).

+4
source share
1 answer

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> 
+3
source

Source: https://habr.com/ru/post/1338852/


All Articles