I am creating an ASP.NET MVC Core web application. I have a form in my View that posts to the Create action in the ProductsController. I am using jquery unobtrusive ajax so my form looks like the following:
<form asp-action="Create" data-ajax="true" data-ajax-method="post" data-ajax-success="onSuccess"></form>
Here is what my Create action looks like:
[HttpPost("Products/Create")]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("Id,Name")] ProductViewModel vm)
{
}
This works completely fine.
However, the following does not:
[HttpPost("Products/Create")]
[ValidateAntiForgeryToken]
public IActionResult Create([FromBody] ProductViewModel vm)
{
}
I get an error in the js console: 415 (Unsupported Media Type). I am assuming this is because when the form is posted it isn't being set w/ Content-Type application/json.
It seems like Microsoft uses the Bind syntax when using their MVCController template and they use the FromBody syntax when using their APIController template.
I rarely use MVC for what it is these days since most of my pages involve ajax. I believe I am better treating my Action Methods more like API calls rather than MVC actions which is why I am trying to use FromBody.
Also, when I post to the FromBody Create action in Postman as Json with content-type application/json it works perfectly.