User-515813820 posted
Hi,
I've created a kind of hack to store one to many records in a junction table using Dynamic Data and Linq. I have a simple checkboxlist control in the _Edit usercontrol. The code looks like this:
Imports System.Web.DynamicData
Imports System.Linq
Imports System.Data.Linq
Partial Class ChildLeadershipLevel_Edit
Inherits System.Web.DynamicData.FieldTemplateUserControl
Protected Overrides Sub ExtractValues(ByVal dictionary As IOrderedDictionary)
dictionary("ResourceLeadershipLevelIDs") = (From chk As ListItem In cblLevels.Items _
Where chk.Selected = True _
Select CInt(chk.Value)).ToList()
End Sub
Protected Sub cblLevels_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles cblLevels.DataBound
Dim dc As New AISDStaffToolDataContext
If TypeOf Me.Row Is Resource Then
Dim currRowID = DirectCast(Me.Row, Resource).TrainingResourceID
Dim selectedLevels = From l In dc.ResourceLeadershipLevels _
Where l.TrainingResourceID = currRowID _
Select l.LeadershipLevelID
For Each level In selectedLevels
cblLevels.Items.FindByValue(level).Selected = True
Next
ElseIf TypeOf Me.Row Is Mentor Then
Dim currRowID = DirectCast(Me.Row, Mentor).MentorID
Dim selectedLevels = From l In dc.MentorLeadershipLevels _
Where l.MentorID = currRowID _
Select l.LeadershipLevelID
For Each level In selectedLevels
cblLevels.Items.FindByValue(level).Selected = True
Next
End If
End Sub
End Class
I know this is kind of a hacked way of doing this since it doesn't handle all cases, but I'm trying to get this done quick and dirty for a client. When I debug, the code works fine to check the correct boxes when selecting a record. The ExtractValues also works fine.
It's getting changed values and putting then back in the database that's a problem. In my partial class that handles Resources for example, I have included this code:
Dim _resourceLeadershipLevelIDs As IEnumerable(Of Integer)
Public Property ResourceLeadershipLevelIDs() As IEnumerable(Of Integer)
Get
End Get
Set(ByVal value As IEnumerable(Of Integer))
_resourceLeadershipLevelIDs = value
End Set
End Property
The setter is firing correctly when the user clicks the Update or Insert button on the page. The problem is if I am not changing any other values on the form, the OnValidate doesn't fire and I can't update the record properly. It also appears that the Resource Object doesn't hydrate, so I can't get the Parent ID to write the records in the junction table.
Any idea of how to get this to work? I'm so close to getting this done it's driving me crazy!
Thanks!