Reputation: 3433
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
Upvotes: 1
Views: 1358
Reputation: 3433
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.
Upvotes: 0
Reputation: 27793
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
Upvotes: 1