I'm encountering some strange behavior in ASP.Net MVC 4.
Based on some information from my viewmodel, I'm trying to set some conditional attributes like so:
<input type="checkbox" data-primary=@(Model.IsPrimary ? "true" : null) checked="@(Model.Selected ? "checked" : null)" disabled="@(Model.Disabled ? "disabled" : null) />
This works fine and dandy for the checked and disabled attribute, but for some reason it'll always render the data-primary attribute. Model.IsPrimary would lead to the correct data-primary="true", but !Model.IsPrimary results in an empty data-primary attribte.
This leads to my first question: What causes this strange behavior? Is it because I'm using a data-attribute? Is it the dash inside the data-attribute?
After that, I thought, "okay, sure, that can easily be fixed", and fixed my code like so:
<input type="checkbox" @(Model.IsPrimary ? "data-primary=\"true\"" : String.Empty) checked="@(Model.Selected ? "checked" : null)" disabled="@(Model.Disabled ? "disabled" : null) />
This fixed my data-primary attribute being shown, but somehow made my disabled and checked attributes show up empty afterwards.
My second question now is What causes this behavior? As far as I can tell, there are no syntax-oddities in my code here.
If anyone has any information on why razor acts this way, please respond.
PS: In the end, I "fixed" things by placing my data-primary attribute at the end of the input element, making everything act as expected.
From the source of Razor 2 in the file HtmlMarkupParser.Block.cs:
private void AttributePrefix(IEnumerable<HtmlSymbol> whitespace, IEnumerable<HtmlSymbol> nameSymbols)
{
// First, determine if this is a 'data-' attribute (since those can't use conditional attributes)
LocationTagged<string> name = nameSymbols.GetContent(Span.Start);
bool attributeCanBeConditional = !name.Value.StartsWith("data-", StringComparison.OrdinalIgnoreCase);
...
}
I don't know why they did this but it seems like it's by design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With