egil / Htmxor

Supercharges Blazor static server side rendering (SSR) by seamlessly integrating the Htmx.org frontend library.
MIT License
130 stars 13 forks source link

Use hx-vals with custom razor component #69

Open salem84 opened 4 weeks ago

salem84 commented 4 weeks ago

Whenever I attempt to use hx-vals with a custom razor component, I get the following error:

RZ9986 Component attributes do not support complex content (mixed C# and markup). Attribute: 'hx-vals', text: '{"CurrentCount":CurrentCount}'

Steps to Reproduce:

  1. Create a custom component
<button class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 focus:bg-gray-700 active:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 transition ease-in-out duration-150">
    @ChildContent
</button>

@code {

    /// <summary>
    /// The content within this component.
    /// </summary>
    [Parameter]
    public RenderFragment? ChildContent { get; set; }
}
  1. Use Htmxor with new custom component (similar code of MinimalHtmxorApp project)
<PrimaryButton class="btn btn-primary"
        hx-put="/counter"
        hx-vals='{ "CurrentCount": @(CurrentCount) }'
        hx-target="#counter"
        @onput="IncrementCount">
    Click me
</PrimaryButton>

Possible solution: Implement a simple method (maybe an external helper or a method in Htmxor.Components.ConditionalComponentBase) to convert to JSON

<PrimaryButton hx-put="/counter"
               hx-vals=@HtmxHelpers.ToJson(new { CurrentCount} )
               hx-target="#counter"
               @onput="IncrementCount">
               Click
</PrimaryButton> 
public static class HtmxHelpers
{
    public static string ToJson(object value) => JsonSerializer.Serialize(value);
}