vendredi 7 juillet 2017

MVC5 Checkbox with label that has nested span

I'm banging my head against a brick wall when it comes to using MVC5 and Razor.

The scenario is so simple using pure HTML :-

<input type="checkbox" name="dd" id="dd">
<label for="dd"><span></span>Accept terms</label>

The above example has custom CSS to change up the styling of the checkbox (not relevant to the problem). The span element is the actual checkbox in my scenario.

I would simply use this method if i could, but there is a client-side validation error label that requires the model bound in an MVC5 format, like so:-

@Html.CheckBoxFor(m => m.AcceptedTerms)
@Html.LabelFor(m=>m.AcceptedTerms)
@Html.ValidationMessageFor(m => m.AcceptedTerms, "", new { @class = "text-danger" })

The problem is, my label requires the span element as its what is being rendered as the checkbox.

I cant see how i can nest a <span> element inside a label this way.

I have tried to do the following :-

@Html.CheckBoxFor(m => m.AcceptedTerms)
 <label for="AcceptedTerms"><span></span>I Agree to the Terms & Conditions</label>

But the label cannot resolve its dependency for a input with the name value set as "AcceptedTerms".

This leads to the span element not being rendered.




Aucun commentaire:

Enregistrer un commentaire