2

I am trying to implement material css to my mvc app, but checkboxfor is giving me hard time. The thing is check box in materialcss has a specific usage setup like this

@for (int j = 0; j < Model.Questions[i].Answers.Count; j++)
{
    <label>
        <input type="checkbox" />
        <span>Red</span>
     </label>
}

if you don't do it like this it won't work, so, naturally I've tried

@for (int j = 0; j < Model.Questions[i].Answers.Count; j++)
    {
    <label>
        @Html.EditorFor(model => Model.Questions[i].Answers[j].IsTrueUserChoice)
        @* or this *@
        @Html.CheckBoxFor(model => Model.Questions[i].Answers[j].IsTrueUserChoice)
        <span></span>
    </label>
}

htm.editorfor and checkboxfor render 2 checkbox tags one is visible and one is hidden (that how checkbox work in mvc), but with materializecss I can't do that because <span></span> has to go bellow <input type="checkbox"/> so this is not going to work because the hidden checkbox field is below checkbox.

Do you have any suggestions on how to fix this?

pgSystemTester
  • 8,979
  • 2
  • 23
  • 49
Stefan Ivovic
  • 87
  • 1
  • 15
  • Looks like whoever implemented checkboxes got a little bit carried away. I don't see how this is possible to achieve. [I would file a issue](https://github.com/Dogfalo/materialize/issues). Title it something like "Razor rendering engine can't render materialize.css checkboxes". PS: also, for completeness, please include the outer for loop with `i` variable in it in the code snippet. – Vanity Slug - codidact.com Jul 23 '18 at 19:54
  • 1
    thanks for comment. filing an issue would take too long, probably wouldnt be fixed. i am sure this can be done with custom html helper – Stefan Ivovic Jul 23 '18 at 20:35
  • Good point. I completely forgot about those. – Vanity Slug - codidact.com Jul 23 '18 at 20:45
  • You need to modify the css to us a sibling selectior. Refer [this answer](https://stackoverflow.com/questions/35550075/how-to-create-an-editortemplate-for-bootstrap-checkbox/35552413#35552413) for an example –  Jul 23 '18 at 22:49
  • @StephenMuecke no luck with that – Stefan Ivovic Jul 24 '18 at 15:58
  • Then you did not modify the css correctly –  Jul 24 '18 at 21:45
  • See this answer for a solution without modifying the css: https://stackoverflow.com/a/53064374/2196799 – chongo2002 Oct 30 '18 at 12:32

1 Answers1

0

Use "DisplayNameFor"...

<label>
    @Html.CheckBoxFor(model => Model.Questions[i].Answers[j].IsTrueUserChoice)
    <span>@Html.DisplayNameFor(model => Model.Questions[i].Answers[j].IsTrueUserChoice)</span>
</label>

And modify the relevant CSS:

label input[type=checkbox].checkbox ~ span:before 
{
    ....
}
Vanderlei Morais
  • 556
  • 6
  • 11