How to use two instances of the same .ascx on the same page in ASP.NET MVC?

I have two controls Address.ascxon an ASP.NET MVC page.

   <h1>Shipping Address</h1>
   <% Html.RenderPartial("Controls/AddressControl"); %>

   <h1>Billing Address</h1>
   <% Html.RenderPartial("Controls/AddressControl"); %>

Of course, with the code, in the same way, I get the same identifiers for each field in the address. I can easily add a string to the field id so I have 'Street1_billing'and 'Street1_shipping', but I don’t understand how to map this to the model.

What is the best solution for comparing a model with an array of elements (in this case only 2). I don't know any ASP.NET out of the box solutions for this.

Note. This is a bit like this question , and I could use this solution from Scott Hanselman , but that’s not quite what I want. In my case, I know that I have two elements, so its essentially 2 arrays of elements, but I wonder if there is a slightly more elegant solution.

PS. I am sure that this has been asked many times before, but I just can’t find the right search terms. Please write this question if you know about it!

+3
source share
2 answers

You may have a ViewModel

OrderCheckoutViewModel
{
    public Address ShippingAddress{get;set;}
    public Address BillingAddress{get;set;}
}

The values ​​of the form elements are displayed on the right side of the ViewModel if they are of the form

<input type="text" name="ShippingAddress.StreetAddress1"><input>

StreetAddress1 ShippingAddress.StreetAddress1. :

public class Address
{
    String StreetAddress1 { get; set }
    String StreetAddress2 { get; set }
    String City { get; set }
    String State { get; set }
    String Zip { get; set }
    String InstanceName{ get; set }
}

InstanceName (ShippingAddress).

<input type="text" name="<%=Model.InstanceName%>.StreetAddress1"><input>

ascx . ,

<% Html.RenderPartial("AddressControl",Model.ShippingAddress); %>

?

+3

.

public class Address
{
    String StreetAddress1 { get; set }
    String StreetAddress2 { get; set }
    String City { get; set }
    String State { get; set }
    String Zip { get; set }
}


Address.ascx , Address, :

<%@ Page Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<MyProject.Models.Address>" %>


ViewData.

Address myAddressObject1 = new Address
{
   AddressLine1 = "123 Anywhere Street",
   // ..etc.  Same with MyAddressObject2.  Or, just populate from database.
}

ViewData["Address1"] = myAddressObject1;
ViewData["Address2"] = myAddressObject2;
//
// do other stuff as needed
//
Return View();


Address :

<%= Html.RenderPartial("Address", ViewData["Address1"]) %>
<%= Html.RenderPartial("Address", ViewData["Address2"]) %>
+4

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


All Articles