总是在同一个项目上(对于那些给我的人),我有一个实体“人”,它与实体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);
}
在添加人员时添加燃料卡有什么想法吗?谢谢!
答案 0 :(得分:0)
如果您要在同一请求上发布Person
和Fuel Card
,则需要在客户端更新您的数据,以便在请求中包含Fuel Card
。
这是在客户端,在服务器端,您可以将Fuel Card
作为嵌套对象添加到Person
(在序列化到客户端时注意循环引用)。
这是一个粗略的例子。在客户端更新您的对象,以包含PersonViewModel
和Fuel Card
。例如,使用javascript:
var person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
添加嵌套对象
person.FuelCard = {property1 ="val1", property2="Val2};
然后使用Ajax将其发布到服务器。
$.post('/Person/Create', person, function(data) {
// do something on success
});