FairyTaz FairyTaz - 5 months ago 103
HTML Question

Open bootstrap Modal from link for each item in a list in view - MVC

I have a view which does a for each loop over a list of database items. I am looking to have a "Details" action for each one which opens a modal passing the id for each item into it and displays the details for that item in a partial view within that modal.

So far I have the following



@foreach (var item in Model)
{
<a href="#detailsModal" role="button" class="btn" data-toggle="modal">Details</a>
}

<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
@{Html.RenderAction("_PartialDetails", "ActivityAds", new { @id = "NEED TO PASS ID HERE" });}
</div>
</div>
</div>
</div>





I am trying to avoid putting the modal in the for each loop as I fear that would be very inefficient having to create a modal for every record. I could be calling the partial view in the Modal wrong as well. I am out of practise Im afraid and I am sure there is a way to do this

Thank you

Answer

One way would be to use ajax to fill in the container dynamically.

here is an example from an app i have - note that some of the javascript is in an external js file so can't directly use model; model values are stored in hidden fields and/or data-id, data-value attributes for this purpose

        @foreach (var assignment in Model.Assignments)
        {                
            <li role="presentation" id="assignmentsDetails_@assignment.AssignmentView.AssignmentViewId" data-id="@assignment.AssignmentView.AssignmentViewId">
                <a role="menuitem" onclick="selectCriteria(this);" title="@assignment.AssignmentView.AssignmentViewDescription">Criteria @criteriaNumber</a>
            </li>
            criteriaNumber++;
        }

javascript

function selectCriteria(clickedElement) {
    var dataid = $(clickedElement).parent().attr("data-id");
    loadAssignmentDetails(dataid);
}

function loadAssignmentDetails(assignmentViewId) {
    $.ajax({
        type: "GET",
        url: Config.RootUrl + "Assignments/Detail/" + assignmentViewId + "/" + $("#AssignmentTypeValueId").val(),
        success: function (data) {
            $("#assignmentViewDetailsContainer").html(data);
        }
    });
}