无法保存部分视图asp.net mvc的更改

时间:2014-05-03 10:41:42

标签: asp.net-mvc

class Address
{
    public int customerId {get;set;}
    public string street {get;set;}
    public string state {get;set;}
}

class Customer
{
    public int customerId {get;set;}
    public string name {get;set;}
    public Address address {get;set;} 
}

客户观点:

@model Models.Customer

@using (Html.BeginForm() 
{
   @Html.HiddenFor(m=>m.curtomerId
   @Html.TextBoxFor(m => m.name)

   @Html.Partial("_Edit", Model)

   <button type="submit">Submit</button>

}

部分:

@model Models.Customer

@Html.HiddenFor(m => m.Address.customerId
@Html.TextBoxFor(m => m.Address.street)
@Html.TextBoxFor(m => m.Address.state)

控制器:

public ActionResult customer(Customer c)
{
     if (ModelState.IsValid)
            {
                db.Entry(c).State = EntityState.Modified;
                db.SaveChanges();

                Address address = db.Address.Single(x => x.customerId== c.Address.customerId);  
                address = c.Address;        
                db.SaveChanges();
                return RedirectToAction("Index");
            }

}

我可以看到所有信息都传递给控制器​​,但是

 db.Entry(model).State = EntityState.Modified;
 db.SaveChanges();

我只是让客户更新了。 所以我补充道:

 Address address = db.Address.Single(x => x.id == c.Address.Id);   
 address = c.Address;
 db.SaveChanges();

但地址信息没有保存,我不知道为什么。

1 个答案:

答案 0 :(得分:0)

检索Address实体并将其分配给address变量。然后将address变量重新分配给c.Address.您从数据库中检索的地址位于上下文中但未被修改,并且您的范围中没有引用。

如果您将检索到的address实体的属性设置为c.Address的属性,那么如果有更改,则会将其标记为已修改。

address.street = c.Address.street;
address.state = c.Address.state;

如果您检查了检索到的地址实体的State,那么您可能会在此时将其视为EntityState.Modified