locked
Tag helpers with nested objects RRS feed

  • Question

  • User1314407993 posted

    I'm using the "asp-for" tag helper, but the boolean property I'm mapping to the control is nested inside an object. Here's an example that should render a checkbox, but instead it's rendering a textbox:

    <input asp-for="Interview.OnTime" class="form-control checkbox-lg" />

    The "OnTime" property of the "Interview" object is a boolean. For some reason, having it nested causes the helper to generate a textbox instead. If I replace that value with a non-nested boolean property, the checkbox is rendered as expected. I can work around this by flattening out my view model, but I'd rather simply fix whatever is causing this error. 

    Wednesday, July 31, 2019 11:00 PM

Answers

  • User1314407993 posted

    I was an idiot. I'd set up the class for Entity Framework code-first, and forgot the two boolean values were nullable. I changed their type, and the tag helper worked as expected. I reviewed the design, and there wasn't a good reason to use a nullable boolean at that point, so I was able to make the switch easily. Maybe I'll write a tag helper that will generate a checkbox from a nullable boolean. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 1, 2019 5:04 PM

All replies

  • User711641945 posted

    Hi WilliamSnell,

    Could you share a simple demo to reproduce your issue?Actually I test the code as bellow and it works well:

    1.Model:

    public class TestModel
        {
            public string Name { get; set; }
            public Interview Interview { get; set; }
        }
    public class Interview
        {
            public bool OnTime { get; set; }
        }

    2.View:

    @model TestModel
        <label asp-for="Interview.OnTime"></label>
        <input asp-for="Interview.OnTime" class="form-control checkbox-lg" />

    3.Result:

    Best Regards,

    Rena

    Thursday, August 1, 2019 2:05 AM
  • User1314407993 posted

    I was an idiot. I'd set up the class for Entity Framework code-first, and forgot the two boolean values were nullable. I changed their type, and the tag helper worked as expected. I reviewed the design, and there wasn't a good reason to use a nullable boolean at that point, so I was able to make the switch easily. Maybe I'll write a tag helper that will generate a checkbox from a nullable boolean. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 1, 2019 5:04 PM