Checked="checked" in Razor
I often see the following Razor-enhanced form markup for writing out input checkboxes, particularly in loops where a given checkbox may be checked or unchecked based on some state in the Model. In the completely real scenario below, I have a form on a webpage where I select fruits for a smoothie:
@foreach(var fruit in Model.AllFruits)
{
var id = "SelectedFruits_" + fruit.Id;
if (Model.SelectedFruits.Contains(fruit.Id))
{
<input id="@id" name="SelectedFruits" type="checkbox" value="@fruit.Id" checked="checked" />
}
else
{
<input id="@id" name="SelectedFruits" type="checkbox" value="@fruit.Id" />
}
}
Alternatively, I can simplify that verbose if/else-ing by creating a variable that represents the presence or absence of the checked="checked"
attribute, using a ternary statement:
@foreach(var fruit in Model.AllFruits)
{
var id = "SelectedFruits_" + fruit.Id;
var isChecked = Model.SelectedFruits.Contains(fruit.Id) ? "checked=\"checked\"" : "";
<input id="@id" name="SelectedFruits" type="checkbox" value="@fruit.Id" @isChecked/>
}
While this does leave you with some functionality in your View, I find it’s much cleaner and more readable than the alternative. If you’re using the checked/unchecked flag for other logic, you can separate it out to its own variable to be used both for the markup ternary and whatever else you need it for. (Or better yet, pull it back to the Model because you shouldn’t have lots of logic into your View.)
Is there a reason this isn’t the common practice? It’s worked for me so far, but I’m concerned there’s something I’m missing. Tell me what you think, or about your favorite Razor cleaner down there in the comments.
Return