【问题标题】:How to handle Ajax request with Razor Pages in ASP.NET Core, 2.0如何在 ASP.NET Core 2.0 中使用 Razor 页面处理 Ajax 请求
【发布时间】:2018-03-17 19:28:42
【问题描述】:

下面我正在尝试在 CustomerModel Razor 页面中对操作方法/处理程序进行发布请求。

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 请求时出错

【问题讨论】:

标签: asp.net-mvc asp.net-core asp.net-core-2.0 razor-pages


【解决方案1】:

我认为您无法访问这样的剃须刀页面操作方法。你可以这样试试吗?

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

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

【讨论】:

  • 感谢@Anuraj 的回答
【解决方案2】:

要调用 handler 你需要添加 handler 关键字。

网址:- /Customer?handler=ListofCustomer

URL :- /Razor 页面名称?HandlerName

【讨论】:

    猜你喜欢
    • 2019-08-02
    • 2018-09-05
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2018-03-30
    • 2012-05-18
    相关资源
    最近更新 更多