LCaraway
LCaraway

Reputation: 1357

asp.net MVC - Dynamically Create Modal and set Event Listener

I have bootstrap modal that gets created depending upon a search the user kicks off. The search returns an HTML table that is embedded in this new modal. Ultimately, upon the user clicking a row <tr> I would like that rows contents be passed into a form using jquery. My issue however is that i am not able to even get the click event to register to the <tr> of which I assign the class result-item. Im assuming this is because the table is created dynamically after the script is parsed but am unsure as to how to compensate.

View

<div id="IHS-Search-Results" class="modal fade" role="dialog">
<div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">IHS Search Results</h4>
        </div>
        <div class="modal-body">
            <p>Select the well from the table bellow to populate form.</p>
            <div id="results-table"></div>
        </div>
        <div class="modal-footer">
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="button" value="Close" data-dismiss="modal" class="btn btn-danger" />
                </div>
            </div>

        </div>
    </div>

</div>

... // did not include unnecessary code

...

@section Scripts {
<script>

    $(document).ready(function () {
        $('#submitModal').click(function () {

            var data = {
                'API14' : $('#API14').val()
            }

            console.log(data)

            $.ajax({
                url: '/IHS_XREF/Search',
                data: data,
                success: function (data) {
                    $('#IHS-Search').modal('toggle');
                    $('#results-table').html(data);
                    $('#IHS-Search-Results').modal('toggle');

                }

            });


        });

        $('.result-item').click(function (e) {

            console.log("click");

            var api = $(this).children('#API').val();
            var entityID = $(this).children('#EntityID').val()
            var prodZone = $(this).children('#ProductionZone').val()
            var lease = $(this).children('#LeaseName').val()
            var wellNo = $(this).children('#WellNum').val()

            $('#api14').val(api);
            $('#entity').val(entityID);
            $('#prod_zone_nm').val(prodZone);
            $('#lease_name').val(lease);
            $('#well_no').val(wellNo);
            $('#ihs-search-results').modal('toggle');

        });
    });

</script>
}

Controller

    [HttpGet]
    public ActionResult Search(string API14)
    {
        IHSProductionSetXrefCreate ps = new IHSProductionSetXrefCreate();

        string[] idArray = new string[] {API14};

        byte[] export = diwh.Download(idArray);

        using (MemoryStream ms = new MemoryStream(export))
        {

            XmlSerializer serializer = new XmlSerializer(typeof(IHSProductionSetXrefCreate));
            try
            {
                IHSProductionSetXrefCreate result = (IHSProductionSetXrefCreate)serializer.Deserialize(ms);
                ps = result;
            }
            catch (Exception e)
            {
                throw new Exception("Generic Exception - Issue with Serialization", e);
            }


        }

        List<IHS_API_SearchResults> searchResults = new List<IHS_API_SearchResults>();
        foreach(var i in ps.ProducingEntity)
        {
            string API = i.WellBore[0].Identification.API;
            string ENT = i.ProdMeta[0].EntityID;
            string ZNE = i.Header[0].Zone.Zone_Name;
            string LSE = i.Header[0].Designation.Designation_Name;
            string WNO = i.WellBore[0].WellNum.WellNum;

            searchResults.Add(new IHS_API_SearchResults {API14 = API, EntityID = ENT, ProductionZone = ZNE, LeaseName = LSE, WellNum = WNO});

        }


        return PartialView(searchResults);
    }

Partial View - Returned to View from Controller

@model List<IHS_DATA_MANAGER.Models.IHS_API_SearchResults>

<table class="table table-bordered table-striped table-hover" id="r-table">
    <thead>
        <tr>
            <th class="text-nowrap">
                @Html.DisplayNameFor(model => model[0].API14)
            </th>
            <th class="text-nowrap">
                @Html.DisplayNameFor(model => model[0].EntityID)
            </th>
            <th class="text-nowrap">
                @Html.DisplayNameFor(model => model[0].ProductionZone)
            </th>
            <th class="text-nowrap">
                @Html.DisplayNameFor(model => model[0].LeaseName)
            </th>
            <th class="text-nowrap">
                @Html.DisplayNameFor(model => model[0].WellNum)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr class="result-item">
                <td id="API">@item.API14</td>
                <td id="EntityID">@item.EntityID</td>
                <td id="ProductionZone">@item.ProductionZone</td>
                <td id="LeaseName">@item.LeaseName</td>
                <td id="WellNum">@item.WellNum</td>
            </tr>
        }

    </tbody>


</table>

@section Scripts {


}

Again, it as if the click event never gets registered to the table row.

Upvotes: 1

Views: 1222

Answers (1)

ProgrammerV5
ProgrammerV5

Reputation: 1962

EDIT 2:

Ok, let's go on a higher level, change the handler to be:

$(document).on('click','.result-item',function(){
    alert(' clicked');
})

if that doesn't work then there is a different problem in your page (another JS error probably).

EDIT: Not sure if it is .table-item or .result-item, on the question you say .table-item but the actual row is .result-item, change accordingly.

As the table is created dynamically you need to use the .on method from jquery instead of .click, like this:

$('.result-item').on('click',function(){
    alert(' clicked');
})

or

$('.table-item').on('click',function(){
    alert(' clicked');
})

Jsfiddle:

https://jsfiddle.net/otax1L3y/

Upvotes: 1

Related Questions