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

谁说我不能喝 提交于 2019-12-04 13:48:56

You can have a ViewModel

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

The values of formelements are mapped to the right Member of the ViewModel if they have the form

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

There is no easy and elegant way to come from StreetAddress1 to ShippingAddress.StreetAddress1. My address model has the form:

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

I set the InstanceName to the Name of the property (ShippingAddress).

Then the form elements are defined in this form

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

The place of the ascx looks uncommon. Any reason why you dont put it in Shared and access it by

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

?

First, add an Address class to the model.

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


In Address.ascx, you need a line at the top that inherits the Address model, like this:

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


In the controller for the main view, push your two addresses into the 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();


In your main view, call your two Address subviews like this:

<%= Html.RenderPartial("Address", ViewData["Address1"]) %>
<%= Html.RenderPartial("Address", ViewData["Address2"]) %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!