Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behavior with conditional data-attributes

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.

like image 690
Kippie Avatar asked Jan 24 '26 04:01

Kippie


1 Answers

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.

like image 128
Magnus Ahlberg Avatar answered Jan 26 '26 18:01

Magnus Ahlberg