我有两个实体:1)学生和 2)地址。
public class Student
{
Public Int StudentId { get; set; }
Public String FullName { get; set; }
Public virtual IList<Address> Addresses { get; set; }
}
public class Address
{
Public Int AddressId { get; set; }
Public Int StudentId { get; set; }
Public String FullAddress { get; set; }
Public virtual Student Student { get; set; }
}
每个学生可能有零个或多个地址。
我想为这两个实体创建单个视图。我知道必须创建一个视图模型。这是视图模型。
public class StudentViewModel
{
Public Int StudentId { get; set; }
Public String FullName { get; set; }
public Address AddAddressModel { get; set; }
Public virtual IList<Address> Addresses { get; set; }
}
我为 StudentViewModel 创建了一个视图。这是学生视图模型:
@model MyProject.Models.StudentViewModel
@{
ViewBag.Title = "Create";
}
@using (Html.BeginForm ())
{
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.FullName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FullName)
@Html.ValidationMessageFor(model => model.FullName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.AddAddressModel.FullAddress)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.AddAddressModel.FullAddres)
@Html.ValidationMessageFor(model => model.AddAddressModel.FullAddres)
</div>
<button id="add">add address to list</button>
<input type="submit" value="save in database" />
</fieldset>
请告诉我如何在 StudentViewModel 的 Addresses 属性中逐个添加一个或多个地址,并在此操作后向用户显示。最后,当我点击“保存在数据库中”按钮时,学生的地址必须插入数据库中。