Skip to content

Commit e9d3a11

Browse files
authored
Merge pull request #2091 from riganti/fix-populate-empty-list
serializer: Fix populate of empty mutable collections
2 parents b00b616 + d4983a4 commit e9d3a11

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

src/Framework/Framework/ViewModel/Serialization/DotvvmCollectionConverter.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,6 @@ public TCollection Populate(ref Utf8JsonReader reader, Type typeToConvert, TColl
165165
var polymorphic = this.polymorphic && !typeof(TElement).IsValueType;
166166

167167
if (existingValue is null ||
168-
existingValue is ICollection { Count: 0 } ||
169168
!polymorphic && GetDefaultConverter(options) is not IDotvvmJsonConverter)
170169
return Read(ref reader, typeToConvert, options, state);
171170

src/Tests/ViewModel/SerializerTests.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,36 @@ public void SupportCollectionPopulate()
399399
Assert.AreEqual("Item2", originalInstances.Item1_.P1); // was "Old2"
400400
}
401401

402+
[TestMethod]
403+
public void EmptyGetOnlyCollectionPopulate()
404+
{
405+
var obj = new TestViewModelWithGetOnlyCollection();
406+
obj.Items.Add(new TestViewModelWithBind { P1 = "new" });
407+
var json = Serialize(obj, out var _, isPostback: true);
408+
409+
var obj2 = PopulateViewModel(json, new TestViewModelWithGetOnlyCollection());
410+
411+
Assert.AreEqual(1, obj2.Items.Count);
412+
Assert.AreEqual("new", obj2.Items[0].P1);
413+
}
414+
415+
[TestMethod]
416+
public void EmptySettableCollectionPopulate_PreservesInstance()
417+
{
418+
var obj = new TestViewModelWithCollections {
419+
ViewModels = new() { new() { P1 = "new" } }
420+
};
421+
var json = Serialize(obj, out var _, isPostback: true);
422+
var obj2 = new TestViewModelWithCollections();
423+
var originalCollection = obj2.ViewModels;
424+
425+
var result = PopulateViewModel(json, obj2);
426+
427+
Assert.AreSame(originalCollection, result.ViewModels);
428+
Assert.AreEqual(1, result.ViewModels.Count);
429+
Assert.AreEqual("new", result.ViewModels[0].P1);
430+
}
431+
402432
[TestMethod]
403433
public void SupportNestedCollectionPopulate()
404434
{
@@ -2061,6 +2091,12 @@ public class TestViewModelWithCollections
20612091
public List<string> Strings { get; set; } = new List<string>();
20622092
}
20632093

2094+
public class TestViewModelWithGetOnlyCollection
2095+
{
2096+
[Bind(Direction.Both)]
2097+
public List<TestViewModelWithBind> Items { get; } = new();
2098+
}
2099+
20642100
public class TestViewModelWithNestedCollections
20652101
{
20662102
public List<List<TestViewModelWithBind>> Matrix { get; set; } = new List<List<TestViewModelWithBind>>();

0 commit comments

Comments
 (0)