Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Ajax request with Razor Pages in ASP.NET Core, 2.0

Below i am trying to make a Post Request to Action Method / Handler inside CustomerModel Razor Pages.

RazorPage name is "Customer.cshtml"

Binding DropdownList from Ajax Request

<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<select class="form-control" id="CustomerID" 
        name="CustomerID" 
        asp-for="Customer.CustomerID"
        asp-items="@(new SelectList(string.Empty,"CustomerID", "Name"))">
</select>

Ajax Request

I also tried to call only handler but it show error

<script type="text/javascript">
$(document).ready(function ()
{
    $.ajax({
            type: 'GET',
            // we are calling json method

            // /Pagename/ActionMethod
            // /Pagename/Handler(OnGetListofCustomer)

            url: '/Customer/OnGetListofCustomer', 
            contentType: "application/json",
            success: function (data) {
                $("#CustomerID").append('<option value="' + "0" + '">' + "Select State" + '</option>');
                debugger;
                $.each(data, function (i, state) {
                    $("#CustomerID").append('<option value="' + state.CustomerID + '">' + state.Name + '</option>');
                });
            },
            error: function (ex) {
                alert('Failed to retrieve states.' + ex);
            }
        });
});

PageModel

CustomerModel

Error While Making Ajax Request

enter image description here

like image 522
Saineshwar Avatar asked Oct 06 '17 04:10

Saineshwar


1 Answers

I don't think you're able to access razor page action method like that. Can you try like this?

$.getJSON("/Customer?handler=ListofCustomer",function(data){
    //Do something with the data.
});

Because to access any methods other than default OnGet or OnPost methods we require handlers, which run-time maps internally to the methods.

like image 115
Anuraj Avatar answered Oct 13 '22 14:10

Anuraj