On a Blazor page, given the following markup:
<button @(SomeObject == null ? "abc" : "xyz")>Click me</button>
If "SomeObject" is null then the button tag should include the "abc" attribute in it, if "SomeObject" is not null, the button tag should include the "xyz" attribute in it.
What really happens is that no attributes are rendered regardless of the "SomeObject" value.
Having this work correctly is particularly important when rendering "disabled" or "selected" attributes since those are standalone attributes.
Ok, so my original issue went something like this:
<option @(SomeObject == null ? "selected" : string.Empty)"> Option Value </option>
I wanted the selected attribute to be included in the option tag if SomeObject was equal to null. The code above does not work. However, after looking at the generated code I changed the markup as follows:
<option selected="@(SomeObject == null ? true : false)"> Option Value </option>
Things now work as expected, however, is this the proper way to go about this?
Thanks.
I would say that <button @(SomeObject == null ? "abc" : "xyz")>Click me</button> should render as:
<button abc>Click me</button> or <button xyz>Click me</button>. You shouldn't be restricted to only applying the value as some attributes are based on the key only.
Hi @rxelizondo the way to do what you're asking is:
C#
<option selected="@(SomeObject == null)"> Option Value </option>
Attributes will render conditionally if the value is a boolean.
We don't support putting arbitrary code inside tag headers, and bug is that this isn't being reported as a compiler error.
Sounds good, Thank you.
Apologies in advance if I'm missing something, but I do think this could be very valuable. I'm setting up a specific data attribute that will be constant throughout my application. In my particular case, I'm setting an attribute called data-vis-field equal to it's API name, so I might do something like:
<div data-vis-field="banner-image">
It would be great if I could make a constant or a variable someplace that would contain the text "data-vis-field", so that I could just do:
<div @APIField="banner-image">
That way if the data attribute ever changed for some reason, I wouldn't have to change it everywhere, just in one place. Also I wouldn't have to worry about misspelling it.
Thanks
Most helpful comment
Hi @rxelizondo the way to do what you're asking is:
C# <option selected="@(SomeObject == null)"> Option Value </option>Attributes will render conditionally if the value is a boolean.
We don't support putting arbitrary code inside tag headers, and bug is that this isn't being reported as a compiler error.