Search code examples
razorhtml-helperrazor-2

How do I (easily) dynamically name helper elements in Razor?


I'm just starting out in Razor, and my first inclination was to treat Helpers like .ACSX's.

Let's say I make a very simple helper:

@helper HowManySpans() {
<div>
<input type="text" name="txtLoops" /><input type="submit" value="how many?" />
@{ if (IsPost) {
    var count = Request["txtLoops"];
    var i = 1;
    while (i < count) {
       <span>Span #@i</span>
       i++;
       }
   }
</div> 
}

It works fine until I place two on the same page. I was expecting the compiler to emit the name of the elements prefixed like ASPX pages generally do, yknow, ctl00_Header_txtLoops or something like that.

I guess in a more argument-driven helper, I could use my arguments to prefix names myself, but I feel that still postpones the issue. If I had some dynamic helper that prefixed names with a certain argument, I could still only have one on a page with that argument.

Am I overlooking something painfully obvious?


Solution

  • Razor emits only the markup that is in the page. It has very little in the way of augmenting the markup. Razor v2 added conditional attributes, but that is still somewhat explicit on behalf of the developer.

    One question I have is why do the elements even need unique names. In many modern HTML5 applications there is little need for elements to have unique names.

    But, suppose, there is a need, there are two ways I can think of to do it:

    1. Have the caller pass in a name or name prefix (as you suggested).
    2. Create your own counter, and increment it every time the helper is called. The big question is where to save the counter's information. One logical place to save it would be the HttpContext.Items collection, which is a per-request "bag of data". Each time the helper is called it checks the Items bag to see what the current count is, increments it by 1, uses that number, and updates the bag.