1

I am making my own shared component. I want to have an input field and a label. Taking the MDN example

<div class="preference">
    <label for="cheese">Do you like cheese?</label>
    <input type="checkbox" name="cheese" id="cheese">
</div>

Fine, but I might have several instances of a shared component on a given page so I need a diffferent id for each instance. I dont see how to do that

pm100
  • 48,078
  • 23
  • 82
  • 145

1 Answers1

2

Generate a guid string and use that:

<div class="preference">
    <label for="@elementId">Do you like cheese?</label>
    <input type="checkbox" name="@elementId" id="@elementId">
</div>

@code { 
    string elementId = Guid.NewGuid().ToString("N");
}
Brian Parker
  • 11,946
  • 2
  • 31
  • 41
  • yup - thx, once i thought about it based on your comment. I have not truly internalized the dynamics of the [bl,r]azor lifecycle. In my head, the HTML gets drawn and then the code runs. Which I know, in my head, is not the case, I need to reset my gut feel – pm100 Jan 20 '22 at 23:05
  • i also fixed the second id – pm100 Jan 20 '22 at 23:06
  • @pm100 Yes this happens to a lot of us when we come from other UI frameworks, – Brian Parker Jan 20 '22 at 23:07
  • This could be a mistake, for HTML5 it is valid though. More here: https://stackoverflow.com/questions/70579/html-valid-id-attribute-values – greenoldman Sep 02 '23 at 12:15