2

I want to create a modal box which has the Title of a Product associated to the button next to the Product when clicked. The data is coming from a database.

I am currently trying to use an integer, which increments on each record in the table, and use this integer to get the record Title. However, I have been unsuccessful to print the currently iterated product.

I'm using bootstrap stylesheets.

Here is a snippet of my code

     foreach (var item in Products)
      .. display Title, Description, Price, button & modal code 
         <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal_@i"> View Product</button>

    <div class="modal fade" id="myModal_@i" role="dialog" data backdrop="false">
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-header">
             <button type="button" class="close" data-dismiss="modal">&times;</button>
               <h4 class="modal-title">View Product</h4>
     ---> @Html.DisplayFor(modelItem => Model.Products.ElementAt(i)) ???? 


          </div>
      <div class="modal-body" id="@i">

Any help would be greatly appreciated.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
fuzzi
  • 1,967
  • 9
  • 46
  • 90
  • why not just use @item.Name istead of use the Htlm helper? – Fals Jul 20 '15 at 21:44
  • 1
    @CodeCaster it seems his problem to create @i where i is the index of each row, as mentioned in the answers below, you can define an index=0 (called count in the answer) and increase it by 1 inside the foreach loop and then you can use this variable to mark your div ids with unique value – Monah Jul 20 '15 at 22:07
  • @Hadi sure, but that's addressed in the duplicate too. OP doesn't seem to _need_ `i`, but used it as part of their solution. – CodeCaster Jul 21 '15 at 07:38

2 Answers2

2

do you want to number each row? if so, you can do the following

@model IEnumerable<YourModel>
@{
  var count =0;
}
<table>
  <thead>
  <tr>
    <th>#</th>
    <th>@Html.DisplayNameFor(m => m.YourField)</th>
   </thead>
  <tr>
  <thead>
  <tbody>
@foreach(var item in Model)
{
  <tr>
   <td>@(count++)</td>
   <td>@Html.DisplayFor(m=> item.YourField)</td>
  </tr>
}
</tbody>
</table>

you can apply what you want based on the above example

so you can use count in the following way in your div

<div id='@(string.Format("model_{0}",count))'>...
user5135401
  • 218
  • 1
  • 9
0

According to the documentation your Product class might need to be annotated to begin to see the behavior you're expecting.

Have you decorated the Product properties that you want to show up?

azarc3
  • 1,277
  • 13
  • 21