PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 28, 2022

[FIXED] Why do I get this warning: '@Model.property' is not a valid value of attribute 'checked'?

 April 28, 2022     asp.net-core, checkbox, compiler-warnings, razor-pages, warnings     No comments   

Issue

I have several checkboxes that I use for display purposes of 'true' and 'false'. Each one will show me the above warning (I made the warning more generic for the purposes of searching. In reality, it reads @Model.Service_Request_Information.Servicelead, etc, instead of @Model.property)

<input class="custom-control-input" type="checkbox" checked="@item.Servicelead" disabled />

I have read that it is okay to write razor code like this, and the HTML will insert/leave out 'checked' from the attributes depending on the value. It works fantastically for how I want it, and it doesn't prevent my code from compiling. So, any ideas on why I am getting this warning?


Solution

Razor will render a boolean attribute if the expression you pass to it evaluates to true. If the expression evaluates to false, the attribute is not rendered at all. That is the Razor feature you are using in your example.

In HTML, valid values for the checked attribute are an empty string or "checked" (Specs) i.e. checked or checked="checked". Visual Studio reports HTML errors as warnings by default, which is what you are seeing. You can either ignore it, turn HTML validation off:

Tools > Options > Text Editor > Html > Validation

Or you can use a ternary expression as demonstrated by other answers:

@(item.Servicelead? "checked" : "")


Answered By - Mike Brind
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing