Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Html data attribute rendering difference

I have experienced a very strange issue which I cannot find the cause of.

In my Asp.Net MVC app (.net4.0/MVC4) I am rending html data attributes within some html element to then be used within the JavaScript.

So in the app I have a Model, e.g.

public class MyModel{
    public bool MyFlag { get; set; }
}

I am then passing this model through onto a simple MVC view page and rendering the boolean value into the html data attribute, e.g.

@model MyProject.MyModel

<a href="#" data-is-flagged="@Model.MyFlag">Click Me</a>

Now when running the project locally the html is rendered as:

<a href="#" data-is-flagged="True">Click Me</a>

However when running on the server, the html is rendered as:

<a href="#" data-is-flagged="data-is-flagged">Click Me</a>

At first I thought that maybe the boolean was not being set somehow, so I added this to the element Click Me @Model.MyFlag which renders as Click Me True. Now I suspected that this has maybe something to do with Debug vs Release mode, however after playing about with this it made no difference.

My fix to this was to change the code to output the boolean value as a string value, e.g. data-is-flagged="@Model.MyFlag.ToString()" which then renders the same locally and on the server.

Any ideas what is the cause of this?

like image 850
Tim B James Avatar asked Oct 19 '22 04:10

Tim B James


1 Answers

I quote the answer from another website:

This is a result of Conditional Attributes that was introduced into Web Pages 2 (MVC 4): http://www.mikesdotnetting.com/Article/201/Cleaner-Conditional-HTML-Attributes-In-Razor-Web-Pages
Two options: revert back to Web Pages 1 (MVC 3) or edit all the affected files.

If the value applied to an attribute is true, the result is that the attribute is repeated (this is useful for the tags option inside a select for instance). If the value set is false, nothing is rendered (not event attribute name).

So, as the comments by @Jamie and @Peter, you may have a different version of the Razor engine in your development enviroment.

like image 54
zed Avatar answered Oct 21 '22 22:10

zed