【问题标题】:How to pass a AJAX Response(true/false) from Controller using ASP .NET CORE如何使用 ASP .NET CORE 从控制器传递 AJAX 响应(真/假)
【发布时间】:2018-11-20 09:25:37
【问题描述】:

我想通过 AJAX 从我的 ASP.NET Core 控制器中检索响应。这是我的代码示例

public IActionResult Submit(ViewModel model) {
    var isValid = true;
    if (isValid) {
        return Json(new {
            success = true
        });
    }
    return Json(new {
        success = false
    });
}

CSHTML 部分

<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
    <input type="text" id="Name" name="Name">
    <input type="text" id="Address" name="Address">
    <input type="text" id="JobDescription" name="JobDescription">
</form>
$("#formSubmit").on('submit', function(e) {
  var datas = {
    Name: $("input[name='Name']").val(),
    Address: $("input[name='Address']").val(),
    JobDescription: $("input[name='JobDescription']").val()
  };
  var formAction = $(this).attr("action");
  $.ajax({
    method: "POST",
    url: formAction,
    data: JSON.stringify(datas),
    dataType: "json",
    contentType: 'application/json',
    success: function(response) {
      if (response.success) {
        alert("Test");
        return true;
      } else {
        alert("Invalid/Error");
        e.preventDefault();
      }
    });
  });

此代码中的问题是重定向/加载到显示{"success":false} 的页面。

我的视图模型

public class ViewModel{
    public string Name { get; set; }
    public string Address { get; set; }
    public string JobDescription { get; set; }
}

【问题讨论】:

  • 尝试在浏览器开发工具中查看返回的确切内容。 ajax 也是异步的,你在成功回调上调用 e.preventDefault()
  • 成功值未成功返回:函数(响应){}
  • e.preventDefault(); 调用作为submit 事件处理程序的第一行。你现在正在回调中执行它,为时已晚。,
  • @RoryMcCrossan 谢谢,我发现我收到 HTTP 错误 400(错误请求)我已经在使用 JSON.stringify,知道吗?
  • @Liam formAction 值为 Home/Submit。查看上面更新的示例代码,我添加了 var formAction = $(this).attr("action");

标签: c# jquery json ajax asp.net-core


【解决方案1】:

这里似乎存在一些问题

<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">

您正在指定 asp-action 和 asp-controller。省略所有这些属性。从以下开始:

<form>...</form>

原因是,当您设置这些属性时,它会使用老式的表单提交机制进行重定向(其中一个会影响您列出)。

名称类型似乎也不匹配,您使用ViewModel,但在您的示例中,类型名称为TFAViewModel

在您的控制器上方(针对每种方法)或在方法本身上方尝试以下添加

[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit([FromBody]ViewModel model)
{
  ModelState.IsValid; //use to inspect. You will also see any violations
  ....

}

在您的 JS 代码中确保执行以下操作(如已评论)

e.preventDefault(); //stops redirect

【讨论】:

  • 抱歉回复晚了。我尝试了您提供的解决方案,现在我收到 HTTP 错误 401(未经授权的错误)。
  • 好的。添加 [AllowAnonymous] 作为 Consumes 上方的另一个属性。当您的错误发生变化时,这总是一个好兆头。表示某事正在取得进展,您离解决方案更近了。您可能在某处有一些默认的 [Authorize] 属性。还要确保您也不需要防伪令牌
  • 是的,我正在使用 [Authorize] 属性。正如你所说,我输入了 [AllowAnonymous],但我仍然收到 HTTP 错误 400(错误请求),我尝试输入 [ValidateAntiForgeryToken] 并仍然收到 HTTP 错误 400(错误请求)。
  • 酷,允许匿名防止 401(未经授权)。现在你有 400 Bad request。这意味着您的模型状态无效。就像我在答案中建议的那样,在第一行添加一个断点并检查 ModelState。很可能 ModelState.IsValid = false,并且您有违规行为。您可以检查 ModelState.Values 中的违规行为。我还注意到您发送 TitleCaseFromJavascript。这是不正确的,你需要发送camelCase(它应该在C#约定和JS约定之间自动解析)祝你好运。
  • 如果您对 camelCase TitleCase 映射有疑问,请将其添加到您的启动文件 services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddJsonOptions(options => { options.SerializerSettings. ContractResolver = new CamelCasePropertyNamesContractResolver(); })
【解决方案2】:

您是否在提交操作中使用了[HttpPost] 属性?您需要设置一个特定的 url,如“/Home/Submit”,并引用 jquery。

行动:

[HttpPost]
    [Consumes("application/json")]
    [Produces("application/json")]
    public IActionResult Submit(ViewModel model)
    {
        var isValid = true;
        if (isValid)
        {
            return Json(new
            {
                success = true
            });
        }
        return Json(new
        {
            success = false
        });
    }

查看:

<form id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
<input type="submit" value="Create" class="btn btn-default" />
</form>

@section Scripts{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
    $("#formSubmit").on('submit', function (e) {
        var datas = {
            Name: $("input[name='Name']").val(),
            Address: $("input[name='Address']").val(),
            JobDescription: $("input[name='JobDescription']").val()
        };
        e.preventDefault();
        //var formAction = $(this).attr("action");
        $.ajax({
            method: "POST",
            url: "/Home/Submit",
            data: JSON.stringify(datas),
            dataType: "json",
            contentType: 'application/json',
            success: function (response) {
                if (response.success) {
                    alert("Test");
                    return true;
                } else {
                    alert("Invalid/Error");
                   // e.preventDefault();
                }
            }
        });
    });
</script>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2019-06-27
    • 1970-01-01
    • 2018-04-18
    • 2021-02-21
    • 2018-01-18
    相关资源
    最近更新 更多