How to pass a nested model value in @Html.Partial

2020-04-11 06:06发布

问题:

I have a model as order inside it I have a another object which I am trying to use in @Html.Partial Code snippet

 public class Order{
   public string Id{set;get;}
   public Address BillingAdress{set;get;}
   public Address ShippingAddress{set;get;}
 }

 public class Address{
   public int Id{set;get;}
   public string Address{set;get;}
 }

IN VIEW

  @model Order
  OrderId: 
  @Html.TextBoxFor(x=>Model.Id)

  ShippingAdress: 
  @Html.Partial("Adress", Model.ShippingAdress)

  BillingAddress:
  @Html.Partial("Adress", Model.BillingAdress)

this is not working . but when I am passing Model instead of Model.ShippingAdress and Model.BillingAdress, TryUpdateModel(Order) is working in controller action can any one tell me why?? I have searched in net but not got any concreete solution so please help me?

回答1:

The reason for that is because the Partial is not respecting the naming convention for the input fields. Use an editor template instead:

@model Order
OrderId: 
@Html.TextBoxFor(x => x.Id)

ShippingAdress: 
@Html.EditorFor(x => x.ShippingAdress)

BillingAddress:
@Html.EditorFor(x => x.BillingAdress)

Now move your Adress.cshtml to ~/Views/Shared/EditorTemplates/Address.cshtml. The name and location of the template is important. It should be located in ~/Views/Shared/EditorTemplates and named the same way as the model type (Address.cshtml):

@model Address
...