【问题标题】:return partial view from async method从异步方法返回部分视图
【发布时间】:2022-01-30 11:44:24
【问题描述】:

我有一个返回部分视图的异步操作方法。 使用 ajax 从函数调用此操作方法。

我的问题:当这个方法被调用时,除了返回的部分视图之外,所有的东西看起来都很好。 我收到错误 500。

这是我的操作方法代码:

[HttpPost]
public async Task<ActionResult> ChangeStateGroup(int[] lstCustomerServiceId, int newState)
{
    int _counter = 0;
    try
    {           
            var _isOk = await CommonFunctions.ChangeState(_customerServiceId, _stateId, string.Empty);

            if (_isOk)
            {
                //------do somthing
            }
        }
        TempData[MyAlerts.SUCCESS] = string.Format("succeed Operation {0}", _counter);
    }
    catch (Exception ex)
    {
        TempData[MyAlerts.ERROR] = string.Format("Error: {0}", ex.Message);
    }
    return PartialView("_AlertsPartial");
}

这是我的 jquery 代码:

function postCustomerChangeStateGroup(lstCustomersId) {
    
    var arrCustomersId = lstCustomersId.split(',');
    $.ajax({
        type: "POST",
        url: "../Customer/ChangeStateGroup",
        data: {
            lstCustomerServiceId: arrCustomersId,
            newState: $("#fk_state").val()
        },
        success: function (data) {
            if (data.indexOf("error") !== -1) {
                $("#inlineAlert_Wrapper").append(data);
            }
            else {
                getCustomerReport();
                $('#modal-container').modal('toggle');
                $("#alert_Wrapper").append(data);
            }
        },
        failure: function (errMsg) {
            alert("An Error Accoured: " + errMsg);
        }
    });
}

【问题讨论】:

    标签: ajax asp.net-mvc async-await partial-views


    【解决方案1】:

    部分视图在 ASP.NET pre-Core 中不能异步。您可以在 ASP.NET Core 中拥有异步局部视图。

    所以,你的选择是:

    1. 更新到 ASP.NET Core。
    2. 删除异步代码并改为同步。

    【讨论】:

    • 天啊。多么糟糕,它很贵。不过谢谢
    【解决方案2】:

    Error 500 表示动作内部的错误。可能是因为输入参数为空。在调试器中检查它们,如果它们为空, 尝试使用 application/json 内容类型,有时效果更好

     $.ajax({
            type: "POST",
             contentType: "application/json; charset=utf-8",
            url: "/Customer/ChangeStateGroup",
            data: JSON.stringify( {
                lstCustomerServiceId: arrCustomersId,
                newState: $("#fk_state").val()
            }),
            success: function (data) {
            ....
    

    创建视图模型

    public class ViewModel
    {
     public int[] lstCustomerServiceId {get; set;}
    public  int newState {get; set;}
    }
    

    并修复操作

    public async Task<ActionResult> ChangeStateGroup([FromBody] ViewModel model)
    

    【讨论】:

    • m sure my input isnt 为空。但我会尝试你的方式并通知你。谢谢
    猜你喜欢
    • 2012-04-28
    • 2014-09-02
    • 2020-04-28
    • 1970-01-01
    • 2012-08-04
    • 2011-09-06
    • 2017-05-12
    • 1970-01-01
    • 2012-09-05
    相关资源
    最近更新 更多