0

i have following mvc page with ajax function which gets called on search button and i am registering two onclick functions when the partial view results are displayed. However, when i click sendSms button, it works the first time and then it does not work. I am assuming that is because the way MVC partial views work and would i have to register it itself in the same way i am register #sendSms in the searchWebPasReferrals function below. However, there must be a better way of implementing this? Could someone please guide?

Parent Page

@model IEnumerable<HDWA.VirtualClinicSystem.PL.ViewModels.WebPASReferralViewModel>

@{
ViewBag.Title = "Referral";
}


@using (Html.BeginForm("SendSMSForClients", "SMS", FormMethod.Post, new { @class = "form-horizontal", role = "form", id = "sendSMSForm" }))
{

<div class="container">
    <div class="row">
        <div class="col-lg-10">
            <section id="Search">
                <hr />
                <div class="form-group col-md-10">
                    @Html.Label("Specialty", new { @class = "col-md-2 control-label" })
                    @Html.DropDownList("Specialty", (SelectList)ViewBag.Specialty, "- Please select -", new { @class = "form-control" })
                </div>


                </div>

                <br />
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="button" value="Search" class="btn btn-primary" id="searchButton" />
                    </div>
                </div>

            </section>
        </div>
    </div>
</div>
<div class="row">
    <div id="loading" style="display:none" class="col-md-2 col-md-offset-5">
        <img src="~/images/ajax-loader.gif" />
    </div>
</div>



<div id="partial">


    @Html.Partial("_ReferralDetail", Model)
</div>
}
@section Scripts {
<script type="text/javascript">

    $(function () {

        $('#bootStartDate').datetimepicker({
            format: 'DD/MM/YYYY'
        });
        $('#bootEndDate').datetimepicker({

            useCurrent: false, //Important! See issue #1075,
            format: 'DD/MM/YYYY'
        });
        $("#bootStartDate").on("dp.change", function (e) {
            $('#bootEndDate').data("DateTimePicker").minDate(e.date);
        });
        $("#bootEndDate").on("dp.change", function (e) {
            $('#bootStartDate').data("DateTimePicker").maxDate(e.date);
        });


        $.ajaxSetup({
            beforeSend: function () {
                // show gif here, eg:
                $("#loading").show();
            },
            complete: function () {
                // hide gif here, eg:
                $("#loading").hide();
            }
        });

    });

    $('#searchButton').click(function (e) {
        searchReferrals(e);
    });



</script>
}

function searchWebPasReferrals(e) {

    $.ajax({
            url: "/SMS/GetDetails/",
            data: { Specialty: Specialty, Name: Name, Code: Code, Priority: Priority, StartDate: StartDate, EndDate: EndDate },
            cache: false,
            type: "post",
            dataType: "html",
            success: function (result) {
                $('#partial').html("");
                $("#partial").html(result);

                //register the events now because of partial view this has to be registered here or inside the partial view itself. 
                //TODO: should refactor this code for better readability
                $('#checkall').click(function () {
                    var chk = $(this).is(':checked');
                    $('input[type=checkbox]', "#referralData").each(function () {
                        if (chk) {

                            $(this).attr('checked', 'checked');
                        }
                        else {
                            $(this).removeAttr('checked');
                        }
                    });

                });

                $('#sendSMS').click(function () {
                    var formData = $('#sendSMSForm').serialize();
                    $.ajax({
                        type: "POST",
                        url: "/SMS/SendSMSForClients",
                        data: formData, //if you need to post Model data, use this
                        success: function (result) {
                            $("#partial").html(result);
                        }
                    });
                });

            },
            error: function (jqXHR, textStatus, errorThrown) {
                $("#partial").html("");
                $('#partial').html('<p>status code: ' + jqXHR.status + '</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>' + jqXHR.responseText + '</div>');
                console.log('jqXHR:');
                console.log(jqXHR);
                console.log('textStatus:');
                console.log(textStatus);
                console.log('errorThrown:');
                console.log(errorThrown);
            },
        });

}

------------------Updated-----------

I have found a solution but not sure if it's a good solution. in the click event for sendSms, i am calling the searchWebPasReferrals(e) on the success, which runs the search again and re-registers the both click events again. Is this a good solution?

3
  • 1
    Give a try by removing @section scripts section
    – Hardik
    Commented Jul 8, 2019 at 4:49
  • or you can use an external js file where you can add this code in $(document).ready(function() { }).
    – Hardik
    Commented Jul 8, 2019 at 4:54
  • the issue with that is because the partial view has not loaded, it does not register. that's why i believe those events have to be registered in the success part of the function?
    – Baahubali
    Commented Jul 8, 2019 at 5:13

1 Answer 1

3

These are my two suggestions.

First you can use this, It worked for me when returning partial views

$(document).on("click", "#sendSMS", function(e){
    /// Do your stuff
});

Second Instead of registering the events on the partial view, include the events in the partial view with JS inline, for example

If you want to attach a click event on sendSms button since it s a button it can be on the view like

<button onclick="DoClick()"><\button>

That way, then you now write the function on you parent page

function DoClick(){
    //do the click actions
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.