总是在同一个项目上(对于那些谁是我的人),我有一个实体“Person”,它与实体 VehicleFuelCard 相关(一对多关系)。在我的“创建人”视图中,我通过 AJAX 代码包含了一个部分视图,它实际上是一个“创建燃料卡”视图:
<script type = "text/javascript">
function AddVehicleFuelCard() {
$("#test").load("@Url.Action("AddVehicleFuelCard","Person",
new { personViewModel = Model })");
}
</script>
并在 PersonController 中调用它:
public ActionResult AddVehicleFuelCard(PersonViewModel personViewModel)
{
ViewBag.Id_VehicleFuelCardCompany = new SelectList(db.VehicleFuelCardCompanies, "Id_VehicleFuelCardCompany", "Name");
return PartialView("PartialVehicleFuelCard", personViewModel);
}
这是我使用的 ViewModel:
public class PersonViewModel
{
private Person _person;
public List<VehicleFuelCard> listVehicleFuelCard;
public Person Person
{
get
{
return this._person;
}
}
public PersonViewModel()
{
this._person = new Person();
}
public PersonViewModel(Person person)
{
this._person = person;
}
public VehicleFuelCard NewVehicleFuelCard
{
get
{
VehicleFuelCard element = new VehicleFuelCard();
element.Person = this.Person;
Person.VehicleFuelCards.Add(element);
return element;
}
}
public PhoneCard NewPhoneCard
{
get
{
PhoneCard element = new PhoneCard();
Person.PhoneCards.Add(element);
return element;
}
}
public ProductAllocation NewProductAllocation
{
get
{
ProductAllocation element = new ProductAllocation();
Person.ProductAllocations.Add(element);
return element;
}
}
}
我的控制器中的创建操作:
public ActionResult Create()
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name");
return View();
}
//
// POST: /Person/Create
[HttpPost]
public ActionResult Create(PersonViewModel personViewModel)
{
if (ModelState.IsValid)
{
db.Persons.AddObject(personViewModel.Person);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", personViewModel.Person.Id_ProductPackageCategory);
return View(personViewModel);
}
在添加人员时添加燃料卡有什么想法吗?谢谢 !