Reputation: 127
I'm having a table in an MVC view like this:
@model FoodCalculator.Models.MealViewModel
@{
ViewBag.Title = "Show Meals";
}
<h2>Meals</h2>
<table class="table table-striped table-hover mealDetailsTable">
<thead>
<tr>
<th>
No
</th>
<th>
Meal name
</th>
<th>
Meal type name
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Meals)
{
<tr id="tableRowClick" data-toggle="modal" data-id="@item.Value" data-target="#mealModal">
<td>
@Html.DisplayFor(modelItem => item.Value.MealID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Value.MealName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Value.MealType.MealTypeName)
</td>
<td>
<button class="btn btn-primary" data-toggle="modal" data-target="#mealModal">Details</button>
}
</tbody>
</table>
And on a row click popup shows up :
@model FoodCalculator.Models.MealViewModel
<div class="modal fade" id="mealDetails" style="display: none; border: 5px solid black; padding: 10px;" role="dialog" aria-labelledby="CmapModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Meal details</h4>
</div>
<div class="modal-body">
<input type="text" id="mealID" name="mealDetail" style="display: none;" />
@if (Model != null)
{
<h3> Meal id : @Model.SelectedMealID</h3>
@Html.Action("ShowMealDetails", "Home", new { mealID = Model.SelectedMealID })
}
Close Save changes
This is all enabled by the javascript :
$('.mealDetailsTable').find('tr[data-id]').on('click', function () {
$('#mealDetails').modal('show');
var getIdFromRow = $(event.target).closest('tr').data('id');
$("#mealID").val(getIdFromRow);
});
And what I'm trying to do is passing viewmodel with currently clicked row data to a popup, so I could perform further actions.
Please help!!!!
Upvotes: 1
Views: 3798
Reputation: 383
Your code has issues. You are trying to generate and create a popup HTML for each of the table rows. But the id of 'data-target' attribute remains the same i.e "#mealModal". What this means is, your popup would be binded by default to the first row of the table. You need to dynamically generate and assign an if to the data-target attribute.
View.cshtml
@model FoodCalculator.Models.MealViewModel
@{
ViewBag.Title = "Show Meals";
var modelPopupId = "#mealModal" + item.Value.MealID; // Considering MealID is unique
var modelPopupReferenceId = "#"+ modelPopupId;
}
// Inside <tbody> element
@foreach (var item in Model.Meals)
{
<tr id="tableRowClick" data-toggle="modal" data-id="@item.Value" data-target="@modelPopupReferenceId">
// All other html elements
}
Popup
div class="modal fade" id="@modelPopupId" style="display: none; border: 5px solid black; padding: 10px;" role="dialog" aria-labelledby="CmapModalLabel" aria-hidden="true">
Upvotes: 2