如何在ASP.NET Core 2.0的Razor Pages中处理Ajax请求

6

我将尝试向CustomerModel Razor Pages中的Action Method / Handler发出Post请求。

RazorPage名称为"Customer.cshtml"

通过Ajax请求绑定DropdownList

<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请求

我也尝试仅调用处理程序,但它显示错误。

<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);
            }
        });
});

页面模型

客户模型

在发起 Ajax 请求时出现错误

输入图像描述


还要记得设置防伪标记,请参见:https://dev59.com/8qXja4cB1Zd3GeqPRXSm - Brad Patton
2个回答

8

我不认为你可以这样访问Razor页面的行为方法。你可以试一下这样:

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

因为要访问除默认OnGet或OnPost方法之外的任何方法,我们需要处理程序,这些处理程序在运行时将内部映射到方法。


感谢@Anuraj的回答。 - Saineshwar Bageri - MVP

1
要调用处理程序,您需要添加handler关键字。
URL:/Customer?handler=ListofCustomer。
URL:/Razor页面名称?HandlerName。

jquery code snippet for calling Get Request


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接