Search code examples
asp.net-mvcrazorhtml-helper

Dynamically Creating IDs in an ASP.net MVC 5 HTML Helper Extension


I will like to dynamically add a unique ID to an hidden field as I loop through a list in the view.

Here's what I have:

@foreach (var food in Model)
            {
                if (counter != 0 && counter % 4 == 0)
                {
                    @:</div>
                    @:<div class="row el-element-overlay m-b-40">
                }

                <!-- /.usercard -->
                              <div class="white-box">
                                  <div class="el-card-item">
                                      <div class="el-card-avatar el-overlay-1">
                                          var theId = "food" + @counter;
                                          @Html.HiddenFor(m => food.Id, new { id = "@{@theId}" })
                                          <img src="@Url.Content("~/Images/"+ @Path.GetFileName(food.FilePath))" />

How can I get append the theID variable or concatenate a string with the @counter to form an Id for the hidden field element.

I have checked here but the OP did not describe what exactly worked in his case.


Solution

  • From a pure syntax point of view, instead of this

    var theId = "food" + @counter;
    @Html.HiddenFor(m => food.Id, new { id = "@{@theId}" })
    

    you can concatenate directly inside the helper:

    @Html.HiddenFor(m => food.Id, new { id = "food" + counter.ToString() })
    

    However,

    from a programming point of view, @Html.HiddenFor(m => food.Id) is incorrect and will render an error. Can you explain why you are trying to render an hidden <input> element? Will it be used to submit a form?