简体   繁体   中英

Ajax POST with ASP.NET Razor

I am developing an ASP.NET core Razor application and I have a form that I am posting, but I don't want the page to reload on submit. I read that this can be avoided by using Ajax, but i'm not sure how to implement this.

This is my form:

<form id="bankDropdown" method="post">
    <div>
        <label class="ratings-text" for="bank">Select Bank:</label>
        <select name="BankOptions" class="form-control ratings-text" style="width:21%" id="bank">
            @foreach (var bank in Model.BankLists)
            {
                <option name="BankOptions" value="@bank.ShortName" id="selection">@bank.ShortName</option>
            }
        </select>
    </div>
    <br />
    <div>
        <label>Enter Start Date:</label>
        <input type="date" asp-for="DateSelect.DateMonthYear1" class="DateMonthYear" name="DateMonthYear1">
        <i data-toggle="tooltip" title="Set to first day of the month for optimal results" class="far fa-question-circle"></i>
    </div>
    <br />
    <div>
        <label>Enter End Date:</label>
        <input type="date" asp-for="DateSelect.DateMonthYear" class="DateMonthYear" name="DateMonthYear" required>
        <i data-toggle="tooltip" title="Set to last or current day of the month for optimal results" class="far fa-question-circle"></i>
    </div>
    <br />
    <div>
        <input class="ratings-button" type="submit" value="Submit"/>
    </div>
</form>

This is my POST function in my page model:

public IActionResult OnPost(string DateMonthYear, string DateMonthYear1, string BankOptions)
        {
            CurrentDate = string.Format(DateMonthYear);
            SelectBank = BankOptions;

            BankLists = ModelService.RunBankList();
            TotalBankCollections = ModelService.RunTotalBankCollection1(DateMonthYear);
            TotalTransactionCounts = ModelService.RunTotalTransactionCount1(DateMonthYear1, DateMonthYear);

            long floatTotalCount = 0;
            int intVolumeCount = 0;
            string stringTotalVolume = "";

            //get individual bank monthly collections
            foreach (var collection in TotalBankCollections)
            {
                if (BankOptions == collection.ShortName)
                {
                    string myBank = collection.TotalCollection;
                    BankCollection = Convert.ToDecimal(myBank).ToString("#,###,###.##");
                }
            }

            //get total collections from all the banks
            foreach (var collection in TotalBankCollections)
            {
                floatTotalCount += (long)Convert.ToDouble(collection.TotalCollection);
                string stringTotalCount = Convert.ToDecimal(floatTotalCount).ToString("#,###,###.##");
                TotalCollectionCount = stringTotalCount;
            }

            //get individual monthly volume collections
            foreach (var collection in TotalTransactionCounts)
            {
                if (BankOptions == collection.ShortName)
                {
                    string myBank = collection.TotalCount;
                    MonthlyVolumeCount = Convert.ToDecimal(myBank).ToString("#,##0");
                }
            }

            //get total transactions of all banks
            foreach (var collection in TotalTransactionCounts)
            {
                intVolumeCount += int.Parse(collection.TotalCount);
                stringTotalVolume = intVolumeCount.ToString("#,##0");
                TotalVolumeCount = stringTotalVolume;
            }

            return Page();
        }

This is what I have so far, I have never used Ajax before and I have a project deadline:

$.ajax({
        type: "POST",
        url: "/Identity/Account/Ratings",
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (response) {
            alert(response);
        },
        failure: function (response) {
            alert(response);
        }
    });

Thanks for the help.

If you want to use ajax with post method in razor page,here is a demo: TestFormPost.cshtml(script):

$("#bankDropdown").on('submit', function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "",
                data: $("#bankDropdown").serialize(),
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (data) {

                }
            });

        })

TestFormPost.cshtml.cs:

public class TestFormPostModel : PageModel
    {
        [BindProperty]
        public List<Bank> BankLists { get; set; }
        [BindProperty]
        public DateSelect DateSelect { get; set; }
        public IActionResult OnGet()
        {
            BankLists = new List<Bank> {
                new Bank{  ShortName="bank1"},
                new Bank{  ShortName="bank2"},
                new Bank{  ShortName="bank3"}
            };
            return Page();
        }
        public IActionResult OnPost(string DateMonthYear, string DateMonthYear1, string BankOptions) {
            return Page();
        }
    }
    public class Bank 
    {
        public string ShortName { get; set; }
    }
    public class DateSelect
    {
        public string DateMonthYear { get; set; }

        public string DateMonthYear1 { get; set; }
    }

result: 在此处输入图像描述

you can prevent form submission by

$('form').on('submit',function(e){
e.preventDefault();

////then ajax call

})

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