MVC模型编辑不保存

时间:2015-10-09 20:48:39

标签: asp.net-mvc vb.net entity-framework

这与this other question I had previously posted ...

有关并且有所不同

我在Site模型中添加了一个新属性,所以这就是现在的样子:

SiteID() As Integer
Name() As String
Latitude() As Double
Longitude() As Double
User() As ApplicationUser

如果您在我的答案中查看设备控制器上的问题 - 创建设备工作正常,并且已为设备正确保存所选的站点。

但是,当我编辑设备并更改所选站点时,该更改不会被保存。

在之前尝试解决此问题时,我添加了一行以从设备中删除该网站,因此这就是编辑帖子现在的样子:

    Async Function Edit(<Bind(Include:="DeviceID,Make,Model,Serial")> ByVal device As Device) As Task(Of ActionResult)
        If ModelState.IsValid Then
            'Because Site is selected in a DropDownFor which only passes the ID integer, need to set the device's site property accordingly
            'Note that with Site being a Navigation property, it looks like it doesn't get saved the way you would think...but it all works
            ModelState.Remove("Site")
            Dim thisSite As Integer = CInt(Request.Form.Get("Site.SiteID"))
            device.Site = (From site In db.Sites Where site.SiteID = thisSite Select site).FirstOrDefault()
            db.Entry(device).State = EntityState.Modified
            Await db.SaveChangesAsync()
            Return RedirectToAction("Index")
        End If
        Return View(device)
    End Function

虽然没有这样做。当我单步执行代码时,设备的网站确实设置正确,所以它看起来很好,但随后索引获取正在获取设备网站的旧值。

为什么这不能妥善保存?

请注意,在Edit中更改设备的其他属性可以正常工作。谢谢!

1 个答案:

答案 0 :(得分:0)

如果Gert Arnold所说的是作为答案发布的,那么我已经将其标记为已被接受。我不知道是这样的! (如果确实这样做会很好)。但无论如何,这里有关于我最终做的事情的细节:

我必须在Device模型中添加一个属性以保存SiteID - 我称之为“SiteNum”。

在创建和编辑帖子中,我只是根据下拉列表中选择的站点设置SiteNum。

因为我想显示与设备关联的站点的名称,所以在Get(创建除外)中我使用SiteNum设置device.Site,更新表,然后在传递给模型的模型中包含Site图。

作为一个例子,这里现在是我在控制器中的索引:

' GET: Devices
Async Function Index() As Task(Of ActionResult)
    'Have to set device's Site here in case user selected a different Site in Edit (which only updates scalar properties)
    Dim sitesList = db.Sites.Include("User").ToList
    'Can't call db.Sites within the For Each because it gives error about it already being open
    For Each item In db.Devices
        item.Site = sitesList.Where(Function(x) x.SiteID = item.SiteNum).FirstOrDefault()
        db.Entry(item).State = EntityState.Modified
    Next
    'Then have to update the database with the sites for the devices so the rest of this stuff will work
    Await db.SaveChangesAsync()
    Dim curUserID = User.Identity.GetUserId()
    'Need to have this include Site so that it will pull in that data in order to reference site name in the View
    '(doing this is called Eager Loading).  Only get devices for sites associated with logged in user.
    Dim devices = db.Devices.Include("Site").Where(Function(x) x.Site.User.Id = curUserID).ToListAsync()
    Return View(Await devices)
End Function

谢谢!