简体   繁体   中英

Asp.net MVC run javascript on button click

I kind of messed up the logic of my code, and I can't figure out how to fix it. I have a Bootstrap navtab panel that when the tabs are clicked, based on which tab is clicked it runs an MVC C# function in my controller. I actually need this to happen on a button click. SO the user enters a date into the datepicker, clicks submit, and then based on which tab is selected, a function will be run. How can I do this on a button click?

Here is my datepicker and button:

<div class="row spiff-datepicksection">
            <div class="col-lg-6 pull-right">
                <div class="col-sm-5 col-lg-offset-4">
                    <div class="form-group">
                        <div class="input-group date">
                            <input id="startDate" type="text" class="form-control" />
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3">
                    <input class="spiffdate-btn" type="submit" value="Submit" />
                </div>
            </div>
        </div>

Here is my javascript:

<script>
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var wrongid = $('.tab-content .active').attr('id');
        $('a[data-toggle="tab"]').removeClass("active");
        $(this).addClass("active");
        var correctid = $(this).data("id");
        alert($('.tab-content .active')[0].outerHTML);

        var startDate = $('#startDate').val();

        if (correctid == "delayedspiff")
            $.get("@Url.Action("DelayedSpiffDate", "Dashboard")", { startDate: startDate });
        else
            $.get("@Url.Action("InstantSpiffDate", "Dashboard")", { startDate: startDate });

    });
</script>

And here is my controller if it is needed:

public ActionResult DelayedSpiffDate(DateTime startDate)
    {
        var available = _appService.GetFeatureStatus(1, "spiffDashboard");
        if (!available)
            return RedirectToAction("DatabaseDown", "Error", new { area = "" });

        var acctId = User.AccountID;
        //startDate = DateTime.Today.AddDays(-6);  // -6
        var endDate = DateTime.Today.AddDays(1); // 1

        Dictionary<DateTime, List<SpiffSummaryModel>> dict = new Dictionary<DateTime, List<SpiffSummaryModel>>();

        try
        {
            var properties = new Dictionary<string, string>
            {
                { "Type", "DelayedSpiff" }
            };
            telemetry.TrackEvent("Dashboard", properties);

            dict = _reportingService.GetDailyDelayedSpiffSummaries(acctId, startDate, endDate);

        }
        catch (Exception e)
        {
            if (e.InnerException is SqlException && e.InnerException.Message.StartsWith("Timeout expired"))
            {
                throw new TimeoutException("Database connection timeout");
            }
            var error = _errorCodeMethods.GetErrorModelByTcError(PROJID.ToString("000") + PROCID.ToString("00") + "001", "Exception Getting DelayedSpiff Dashboard View", PROJID, PROCID);
            error.ErrorTrace = e.ToString();
            _errorLogMethods.LogError(error);
            return RedirectToAction("index", "error", new { error = error.MaskMessage });
        }

        var spiffDateModels = new List<DelayedSpiffDateModel>();

        foreach (var entry in dict)
        {
            var spiffDateModel = new DelayedSpiffDateModel();

            spiffDateModel.Date = entry.Key;

            spiffDateModel.Carriers = new List<DelayedSpiffCarrierModel>();

            foreach (var item in entry.Value)
            {
                var spiffCarrierModel = new DelayedSpiffCarrierModel();
                spiffCarrierModel.Carrier = item.CarrierName;
                spiffCarrierModel.CarrierId = item.CarrierId;
                spiffCarrierModel.ApprovedSpiffTotal = item.ApprovedSpiffTotal;
                spiffCarrierModel.EligibleActivationCount = item.EligibleActivationCount;
                spiffCarrierModel.IneligibleActivationCount = item.IneligibleActivationCount;
                spiffCarrierModel.PotentialSpiffTotal = item.PotentialSpiffTotal;
                spiffCarrierModel.SubmittedActivationCount = item.SubmittedActivationCount;
                spiffCarrierModel.UnpaidSpiffTotal = item.UnpaidSpiffTotal;
                spiffDateModel.Carriers.Add(spiffCarrierModel);
            }

            spiffDateModels.Add(spiffDateModel);
        }
        spiffDateModels = spiffDateModels.OrderByDescending(x => x.Date).ToList();

        return PartialView(spiffDateModels);
    }

Any ideas on how to make this happen on a button click?

You can try to create a handler of the 'click' event, which should retrieve a valid identifier of the selected tab and send a GET request to the server.

$(".spiffdate-btn").click(function(){
    var correctid = $(".tab-content .active").attr("id");
    var startDate = $("#startDate").val();
    if (correctid == "delayedspiff")
        $.get("@Url.Action("DelayedSpiffDate", "Dashboard")", { startDate: startDate });
    else
        $.get("@Url.Action("InstantSpiffDate", "Dashboard")", { startDate: startDate });
});

I realize this is an old question, but I am struggling with a similar issue so I am looking at old questions.

I think I see your problem though:

<script>
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

Your script calls "on shown".

If you do not want it running when it is shown, change it to "on click".

How? I can't help you with that yet. My javascript isn't that good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM