我try 使用AJAX请求的Success和Failure块.我的函数正在工作,我可以很容易地直接指向控制器,并使用我的查询来修改我的SQL数据库,例如.一切正常,这就是我之前没有注意到AJAX响应的原因.

正如我所说的,我可以毫无问题地执行我的操作,但是我的AJAX总是返回失败,即使我的操作正在工作.我不明白怎么修,你能帮我看看吗?

error

一开始,我试着把这个记录下来

console.log('Question sending failed:', result.message);

发送ProductDetail?ProductID=7:2879的问题 失败:未定义

然后我试着把这个记录下来

console.log('the entire result: ', result);

整个ProductDetail?ProductID=7:2880 结果:真

如果我同时记录这两个日志(log),结果就是

整个ProductDetail?ProductID=7:2880 结果:真

您可以看到代码中的更改

action

[HttpPost]
[Authorize]
public async Task<IActionResult> SendEmployeeQuestion(SetEmployeeQuestionQuery request)
{
    var result = await MediatrSend(request);
    return Json(result);
}

returns

enter image description here

对于"Return Json(Result)",也是"true"

query

public class SetEmployeeQuestionQuery : IRequest<bool>
    {
        public ClaimModel ClaimModel { get; set; }
        public int ProductId { get; set; }
        public int FirmId { get; set; }
        public string QuestionText { get; set; }
    }

    public class SetEmployeeQuestionQueryHandler : IRequestHandler<SetEmployeeQuestionQuery, bool>
    {
        private readonly IECommerceProductRepository _eCommerceProductRepository;
        public SetEmployeeQuestionQueryHandler(IECommerceProductRepository eCommerceProductRepository)
        {
            _eCommerceProductRepository = eCommerceProductRepository;
        }
        public async Task<bool> Handle(SetEmployeeQuestionQuery request, CancellationToken cancellationToken)
        {
            DateTime currentDateTime = DateTime.Now;
            string formattedTimestamp = currentDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

            var questionId = _eCommerceProductRepository.InsertToEmployeeQuestion(request.ClaimModel.EmployeeId, formattedTimestamp).Result;

            await _eCommerceProductRepository.InsertToAnswerLog(null, questionId, request.FirmId, request.QuestionText, null);

            return true;
        }
    }

script

// Ask to seller modal
        $(document).ready(function () {
            $('.ask-button').on('click', function () {
                $('#askToSellerModal').modal('show');
            });

            $('#askToSellerModal').on('hidden.bs.modal', function () {
                clearTextarea();
            });

            $('#sendQuestionButton').on('click', function () {
                var productId = "@Model.ProductData.Id";
                var firmId = "@Model.ProductData.FirmId";
                var questionText = $('#askToSellerTextArea').val();

                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("SendEmployeeQuestion")',
                    data: {
                        ProductId: productId,
                        FirmId: firmId,
                        QuestionText: questionText
                    },
                    success: function (result) {
                    if (result.success) {                           
                        console.log('Question sent successfully:', result.message);
                        console.log('the entire result: ', result);
                    } else {
                        console.log('Question sending failed:', result.message);
                        console.log('the entire result: ', result);
                    }
                },
                    error: function (error) {                       
                        console.error('AJAX error:', error.statusText);
                    }
                });

                clearTextarea();
                $('#askToSellerModal').modal('hide');
            });
        });

        function clearTextarea() {
            document.getElementById('askToSellerTextArea').value = '';
        }

推荐答案

这可能是因为在您的async Task<IActionResult> SendEmployeeQuestion中,您将返回一个结果,但您没有设置状态和消息,因此您可以在以后的AJAX响应中处理它.您不是在向您的响应传递消息.因此,您需要稍微更改您的函数才能以这种方式使用.

我已经为您的HttpPost函数设置了try catch个异常块,以便您可以在请求失败时处理错误.这意味着它将进入您的AJAX的错误块.

由于您没有提到您的MediatrSend函数做什么,我假设它会发回一个HttpStatusCode.

     public class BaseResponse
    {
       public bool status { get; set; }
       public string message { get; set; }
   }


     [HttpPost]
     [Authorize]
     public async Task<IActionResult> SendEmployeeQuestion(SetEmployeeQuestionQuery request)
     {

       BaseResponse resp = new BaseResponse();
       try {
            var resultContent = await MediatrSend(request);
            var jsonResponse = resultContent.Content.ReadAsStringAsync();

            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                resp = JsonConvert.DeserializeObject<BaseResponse>(jsonResponse.Result);
                resp.status = true;
                resp.message = "Success message.";
            }
            else
            {
                resp = new BaseResponse();
                resp.status = false;
                resp.message = "error message";
            }
       } catch (Exception ex) {
            resp = new BaseResponse();
             resp.status = false;
            resp.message = $"error in response {Ex.Message}"; 
        }
      
       return resp;
    }

因此,您的AJAX代码应该这样编写:

              $.ajax({
                type: 'POST',
                url: '@Url.Action("SendEmployeeQuestion")',
                data: {
                    ProductId: productId,
                    FirmId: firmId,
                    QuestionText: questionText
                },
                success: function (result) {
                  if (result.status === true) {                           
                    console.log('Question sent successfully:', result.message);
                    console.log('the entire result: ', result);
                   } else {
                    console.log('Question sending failed:', result.message);
                    console.log('the entire result: ', result);
                   }
                },
                error: function (error) {                       
                    console.error('AJAX error:', error.message);
                }
            });

我希望我的例子能或多或少地指导你找到解决问题的办法.

Asp.net相关问答推荐

无法翻译 LINQ

如何从 Azure 上托管的应用服务获取登录用户名?

如何将标头中的用户名/密码传递给 SOAP WCF 服务

分层架构中的 ASP.NET 和实体框架 - 仅将实体框架用于 ORM

WebResource.axd 上的填充无效且无法删除异常

RNGCryptoServiceProvider - 随机数审核

如何异步渲染局部视图

是否可以访问位于另一个项目中的 MVC 视图?

如何将配置转换应用于外部配置文件

ASP.NET IIS - 请求何时排队?

使用 NancyFx 的好处?

asp.net Button OnClick 事件未触发

如何使用 asp.net 获取 html Select 的选定值

HttpResponse.End 或 HttpResponse.Close 与 HttpResponse.SuppressContent

如何获取当前登录用户的角色列表

如何验证 WebClient 请求?

为什么 HttpWebRequest 会抛出异常而不是返回 HttpStatusCode.NotFound?

elmah:没有 HttpContext 的异常?

Page.IsPostBack 和 Page.IsCallBack 有什么区别?

如何创建代表 colored颜色 的随机十六进制字符串?