.Net Core 3.0 AJAX POST Body Always Null

倖福魔咒の 提交于 2020-06-16 17:07:40

问题


I've recently converted my project from .Net Framework 4.7 to .Net Core 3.0. I'm having trouble getting my AJAX post to work.

Here is what's working in .Net Framework 4.7:

View:

@using (Ajax.BeginForm("Save", "Controller", new AjaxOptions() { HttpMethod = "Post", OnSuccess = "OnSaveSuccess", OnFailure = "OnFailure" }, new { Model }))
{
  ... Model Code Here
}

Controller:

[HttpPost]
public JsonResult Save(Contract contract)

Here's what is not working in .Net Core 3.0:

View:

<form method="post" action="/Controller/Save" data-ajax="true" data-ajax-method="post" data-ajax-sucess="OnSaveSuccess"  data-ajax-failure="OnFailure">

Controller:

[HttpPost]
public JsonResult Save([FromBody] Contract contract)

The Contract object comes as NULL in this request. Is there something I'm doing wrong?

Thanks


回答1:


You can refer to the following example to perform ajax submission using jQuery Unobtrusive AJAX.

<form method="post" action="/Home/Save" data-ajax="true" data-ajax-method="post" data-ajax-success="OnSaveSuccess" data-ajax-failure="OnFailure">
    <div class="form-group row">
        <label asp-for="Name" class="col-sm-3 col-form-label"></label>
        <div class="col-sm-7">
            <input asp-for="Name" class="form-control">
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Email" class="col-sm-3 col-form-label"></label>
        <div class="col-sm-7">
            <input asp-for="Email" class="form-control">
        </div>
    </div>
    <div class="form-group row">
        <div class="col-sm-7 offset-sm-3">
            <button class="btn btn-primary" id="submit">Submit</button>
        </div>
    </div>
</form>

obtain and reference jquery-ajax-unobtrusive

@section scripts{
    <script src="~/lib/jquery-ajax-unobtrusive/dist/jquery.unobtrusive-ajax.js"></script>
    <script>
        function OnSaveSuccess(res) {
            console.log(res);
            alert('Success');
        }

        function OnFailure() {
             alert('failed');
        }
    </script>
}

Contract class

public class Contract
{
    public string Name { get; set; }
    public string Email { get; set; }
}

Controller Action (with [FromForm] attribute)

[HttpPost]
public JsonResult Save([FromForm] Contract contract)
{
    // code logic here
}

Test Result




回答2:


It ended up being my fault. I had put:

$.ajaxSetup({
   contentType: "application/json"
});

This was causing the POST to not map properly. Once I removed it the Model came over correctly.



来源:https://stackoverflow.com/questions/60104144/net-core-3-0-ajax-post-body-always-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!