For components, allow attribute values to be arbitrary objects

This commit is contained in:
Steve Sanderson 2018-01-26 09:54:35 -08:00
parent 1b4fa4781a
commit 3940ca8b60
3 changed files with 26 additions and 6 deletions

View File

@ -102,8 +102,20 @@ namespace Microsoft.AspNetCore.Blazor.RenderTree
/// <param name="value">The value of the attribute.</param>
public void AddAttribute(int sequence, string name, object value)
{
AssertCanAddAttribute();
Append(RenderTreeNode.Attribute(sequence, name, value.ToString()));
if (_lastNonAttributeNodeType == RenderTreeNodeType.Element)
{
// Element attribute values can only be strings or UIEventHandler
Append(RenderTreeNode.Attribute(sequence, name, value.ToString()));
}
else if (_lastNonAttributeNodeType == RenderTreeNodeType.Component)
{
Append(RenderTreeNode.Attribute(sequence, name, value));
}
else
{
// This is going to throw. Calling it just to get a consistent exception message.
AssertCanAddAttribute();
}
}
/// <summary>

View File

@ -106,6 +106,14 @@ namespace Microsoft.AspNetCore.Blazor.RenderTree
AttributeValue = value
};
internal static RenderTreeNode Attribute(int sequence, string name, object value) => new RenderTreeNode
{
Sequence = sequence,
NodeType = RenderTreeNodeType.Attribute,
AttributeName = name,
AttributeValue = value
};
internal static RenderTreeNode ChildComponent<T>(int sequence) where T: IComponent => new RenderTreeNode
{
Sequence = sequence,

View File

@ -684,9 +684,9 @@ namespace Microsoft.AspNetCore.Blazor.Test
var diff = new RenderTreeDiffComputer(renderer);
var testObject = new object();
newTree.OpenComponentElement<FakeComponent>(0);
//newTree.AddAttribute(1, nameof(FakeComponent.IntProperty), 123);
newTree.AddAttribute(1, nameof(FakeComponent.IntProperty), 123);
newTree.AddAttribute(2, nameof(FakeComponent.StringProperty), "some string");
//newTree.AddAttribute(3, nameof(FakeComponent.ObjectProperty), testObject);
newTree.AddAttribute(3, nameof(FakeComponent.ObjectProperty), testObject);
newTree.CloseElement();
// Act
@ -696,9 +696,9 @@ namespace Microsoft.AspNetCore.Blazor.Test
// Assert
AssertEdit(result.Edits.Single(), RenderTreeEditType.PrependNode, 0);
Assert.NotNull(componentInstance);
//Assert.Equal(123, componentInstance.IntProperty);
Assert.Equal(123, componentInstance.IntProperty);
Assert.Equal("some string", componentInstance.StringProperty);
//Assert.Same(testObject, componentInstance.ObjectProperty);
Assert.Same(testObject, componentInstance.ObjectProperty);
}
[Fact]