I am attempting to AJAX JQuery post some form data to my MVC controller but I’m getting an error of 400. I am attempting to post by doing:
var count = $('#MediaList').children().length;
for (var i = 0; i < count; i++) {
$.post('/Submit/MediaAdd',
{ model: $('.AddMedia:nth-child(' + i + ')').find('form').serialize(), count: count }
);
}
The information is supposed to go into this method:
[Route("/Submit/MediaAdd")]
[ValidateAntiForgeryToken] //Add media form handler
public IActionResult MediaAdd(Media model, int count)
{
if (ModelState.IsValid)
{
//do stuff to model and count
}
}
Finally, here is a shortened version of my form:
<form name="mediaAdd" method="post">
@Html.AntiForgeryToken()
<div class="container">
<div class="form-row">
<label asp-for="Medias.Blurb" class="control-label">Blurb
<span class="text-danger ml-1">*</span>
<span class="text-muted ml-1">Explain what is in the media</span>
</label>
<input asp-for="Medias.Blurb" class="form-control" />
<span asp-validation-for="Medias.Blurb" class="text-danger"></span>
</div>
<div class="form-row col-5">
<div class="form-group MediaLink">
<label for="FileLink">Link the Media</label>
<input asp-for="Medias.SourceFile" type="url" class="form-control" id="FileLink">
</div>
</div>
</div>
</form>
2
Answers
It took three things to fix it fully. First remove the
Medias.
from the front of the asp-for. Secondly, the Controller Method wants an input in the form of a JSON array. So I had to convert the serialized output to a JSON array. Lastly, I need to validate the input, meaning that I need to pass the verification token to the method, I stole the code for that from user Yiyi You. This can be done by the following code:Maybe it is caused by
{ model: $('.AddMedia:nth-child(' + i + ')').find('form').serialize(), count: count }
.Here is a demo worked:Media.cs:
Controller:
View:
result: