0

Is it possible to use two models in the same view (my view is strongly-typed to a model of mine and i need to modify another model in the same view). Is there a way to do this

2 Answers 2

2

Use a ViewModel which has properties to represent your other models and pass an object of that to the View.

public class CustomerViewModel
{
  public int ID { set;get;}
  public string Name { set;get;}
  public Address Address {set;get;}
  public IList<Order> Orders {set;get;}

  public CustomerViewModel()
  {
     if(Address==null)
         Address=new Address();

     if(Orders ==null)
         Orders =new List<Order>();
  }
}

public class Address 
{
  public string AddressLine1 { set;get;} 
  //Other properties 
}

public class Order
{
  public int OrderID{ set;get;} 
  public int ItemID { set;get;}
  //Other properties 
}

Now in your Action method

public ActionResult GetCustomer(int id)
{
   CustomerViewModel objVM=repositary.GetCustomerFromId(id);
   objVm.Address=repositary.GetCustomerAddress(id);
   objVm.Orders=repositary.GetOrdersForCustomer(id);
   return View(objVM);
}

Your View will be typed to CustomerViewModel

@model CustomerViewModel
@using(Html.BeginForm())
{
  <h2>@Model.Name</h2>
  <p>@Model.Address.AddressLine1</p>
  @foreach(var order in Model.Orders)
  {
    <p>@order.OrderID.ToString()</p>
  }

}
Sign up to request clarification or add additional context in comments.

Comments

1

Create one model that combines the two models. That's pretty common:

 public class CombinedModel
    {

        public ModelA MyFirstModel { get; set; }
        public ModelB MyOtherModel { get; set; }


    }

1 Comment

Also referred to as a "ViewModel"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.