0

总是在同一个项目上(对于那些谁是我的人),我有一个实体“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);
}

在添加人员时添加燃料卡有什么想法吗?谢谢 !

4

1 回答 1

0

如果您想在同一请求中同时发布帖子PersonFuel Card则需要在客户端更新您的数据以包含Fuel Card在您的请求中。

那是在客户端,在服务器端,您可以将其添加Fuel Card为嵌套对象Person(尽管在序列化到客户端时要注意循环引用)。

这是一个粗略的例子。在客户端更新您的对象以同时包含PersonViewModelFuel 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
 });
于 2013-03-04T15:13:36.623 回答