0

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.

Alfred Wallace
  • 1,741
  • 1
  • 14
  • 32
Samseen
  • 87
  • 5
  • 13
  • Are you getting an error? – Alfred Wallace Aug 23 '18 at 16:17
  • What are you trying to do here? You cannot get 2-way model binding using a `foreach` loop (refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943)). The purpose of `id` attributes are for css and jquery selectors which make no sense in a dynamic loop –  Aug 23 '18 at 21:58
  • I've explained in the comment that I'm trying to hide some data I got from the controller till the time I'll be triggering the visibility with jquery. – Samseen Aug 28 '18 at 18:45

1 Answers1

0

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?

Alfred Wallace
  • 1,741
  • 1
  • 14
  • 32
  • I need to use the Id on the view at a later time and it should first be loaded from the controller. It's hidden because I don't want it to be visible, just trying to keep it in an HTML element. – Samseen Aug 28 '18 at 18:39