Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - How to pass a nested model value in @Html.Partial

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...