Csharp/C#教程:ASP.NET MVC在一个视图中创建具有相关对象的对象分享


ASP.NET MVC在一个视图中创建具有相关对象的对象

我是ASP.NET MVC的新手,我想创建一个视图,我可以在其中创建一个新对象以及相关对象。

例如:我有以下类Person:

public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual List
Addresses { get; set; } }

和class级地址:

 public class Address { public int AddressId { get; set; } public string City { get; set; } public string Street { get; set; } public int PersonId { get; set; } public virtual Person Person { get; set; } } 

我想要实现的是拥有一个视图,用户可以输入该人的数据和该用户的任意数量的地址。

我的第一个(简单)尝试只是提供一个映射到控制器方法的动作链接。 此方法将Person对象作为参数,将Address对象添加到集合Addresses并返回一个新的create视图(可能不太好,但这很有效)。 但是当我尝试添加第二个地址时,我注意到Person的地址集合再次为空。

针对此类问题的任何sugesstions / best practice?

谢谢!

我建议你采用以下方法:

1.创建一个视图模型:

 public class AddressViewModel { public string City { get; set; } public string Street { get; set; } } public class PersonViewModel() { public string FirstName { get; set; } public string LastName { get; set; } public AddressViewModel AddressViewModelTemplate {get; set;} public Collection Addresses {get; set;} } 

然后在您的视图中,您可以使用隐藏的EditorTempalete作为AddressViewModelTemplate ,并在某些按钮单击时使用javascript显示它。 当然,您必须为绑定调整生成的集合的名称。

样本编辑器模板。 你可以选择更好的结构。

  @model AddressViewModel 
@Html.LabelFor(x => x.City)
@Html.TextBoxFor(x => x.City)
@Html.LabelFor(x => x.Street)
@Html.TextBoxFor(x => x.Street)

在您的强类型视图中:

上述就是C#学习教程:ASP.NET MVC在一个视图中创建具有相关对象的对象分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 @model PersonViewModel; @using(Html.BeginForm()) { //Display textbox for Person properties here .... 
@Html.EditorFor(x => x.AddressViewModelTemplate)
....
}

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/985443.html

(0)
上一篇 2021年12月21日
下一篇 2021年12月21日

精彩推荐