简体   繁体   中英

In ASP.NET Razor Page Jquery Ajax Function not Working

I have a two onchange function for a page called create delivery request. One is when the dropdownlist of receiver changes, then it should show the phone number & address of receiver selected. Another one is when the dropdownlist of delivery item changes, then it should set the max attribute for the quantity. The url of both these are linked to the customized OnGet method in razor page.

However, usually the above Onget method is hit but the below one is not. And the above OnGet method can't get the dryfood with the passed ID as well, it is null inside. And the two jQuery ajax function doesn't work at all. I'm totally a beginner. Hope that there is someone who can help me. Thanks in advance.

In create.cshtml :

<div class="mb-3">
    Receiver Name
    <select id="receiver" asp-for="Delivery.ReceiverID" asp-items="Model.ReceiverList" class="form-control">
        <option>--Select the Receiever--</option>
    </select>
</div>
<div class="mb-3">
    Receiver Phone
    <span id="receiverphone" class="form-control">----</span>
</div>
<div class="mb-3">
    Receiver Address
    <div id="receiveradrs1" class="form-control">----</div>
    <div id="receiveradrs2" class="form-control">----</div>
</div>
<div class="mb-3">
    Delivery Item
    <select id="deliveryitem" asp-for="DeliveryItem.DryFoodID" asp-items="Model.DeliveryItemList" class="form-control">
        <option>--Select Delivery Item--</option>
    </select>
</div>
<div class="mb-3">
    Quantity
    <input id="quantity" asp-for="DeliveryItem.Quantity" min="1" class="form-control" />
</div>

In create.csthml.cs , two customized OnGet method here:

public async Task<IActionResult> OnGetSetMaxQuantity(int id)
{
    List<DryFoodDonation> dfdlist = await _db.DryFoodDonation.ToListAsync();
    var dryfood = dfdlist.Where(d => d.Id == id).FirstOrDefault();
    Debug.WriteLine(dryfood.DryFoodName + " " + dryfood.DryFoodRemainQuantity);
    return new JsonResult(dryfood.DryFoodRemainQuantity);
}

public async Task<IActionResult> OnGetGetPhoneAdrs(int id)
{
    List<User> receiverlist = await _db.User.Where(u => u.UserType.TypeID == 3).ToListAsync();
    var selectreceiver = receiverlist.Where(d => d.UserID == id).FirstOrDefault();
    Debug.WriteLine(selectreceiver.UserName + " " + selectreceiver.UserPhone);
    return new JsonResult(selectreceiver);
}

The jQuery AJAX function in a JavaScript file:

$(document).ready(function () {
    $("#receiver").change(function () {
        alert('Yes receiver here changed.');
        var item = $(this).val();
        $.ajax({
            type: 'GET',
            url: 'Create/?handler=GetPhoneAdrs',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: {
                'id': item
            },
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                $('#receiverphone').html(data.UserPhone);
                $('#receiveradrs1').html(data.UserAdrs1);
                $('#receiveradrs2').html(data.UserAdrs2);
            }
        });
    });

    $("#deliveryitem").change(function () {
        alert('Yes item here changed.');
        var item = $(this).val();
        $.ajax({
            type: 'GET',
            url: 'Create/?handler=SetMaxQuantity',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: {
                "id": item
            },
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                $("#quantity").attr({
                    "min": 1,
                    "max": data
                });
            }
        });
    });
});

Please help me with this. I can't solve this problem for a few weeks. Thank you!

// cshtml.cs 

const sendMe = async function (someData) {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/ControllerName/MethodNameInController',
        data: { someData: someData },
        success: function (response) {
            if (response != null && response.statusCode == 200) {
                ..
            } else {
                ..
            }
        }
    });
}


//Controller
[HttpPost("MethodNameInController")]
public IActionResult MethodNameInController([FromForm] string someData) {
..
}

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