skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    function SubmitMedia () {
            var count = $('#MediaList').children().length;
            var token = $('input[name="__RequestVerificationToken"]').val();     
            for (var i = 0; i < count; i++) {
            var data = $('.AddMedia:nth-child(1)').find('form').serialize().split("&");
            console.log(data);
            var obj = {};
            for (var key in data) {
                console.log(data[key]);
                obj[data[key].split("=")[0]] = data[key].split("=")[1];
            }
            console.log(obj);
                $.post('/Submit/MediaAdd',
                    { __RequestVerificationToken: token, model: obj, count: count },
                );
            }
        }
    

  2. Maybe it is caused by { model: $('.AddMedia:nth-child(' + i + ')').find('form').serialize(), count: count }.Here is a demo worked:

    Media.cs:

    public class Media
        {
            public string Blurb { get; set; }
            public string SourceFile { get; set; }
        }
    

    Controller:

     [Route("/Submit/MediaAdd")]
            [ValidateAntiForgeryToken] //Add media form handler
            public IActionResult MediaAdd(Media model, int count)
            {
                if (ModelState.IsValid)
                {
                    return Ok();
                }
                return Ok();
            }
            
    

    View:

    @model Media
    @{
        ViewData["Title"] = "Media";
    }
    
    <h1>Media</h1>
    <form name="mediaAdd" method="post" id="dataForm">
        @Html.AntiForgeryToken()
        <div class="container">
            <div class="form-row">
                <label asp-for="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="Blurb" class="form-control" />
                <span asp-validation-for="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="SourceFile" type="url" class="form-control" id="FileLink">
                </div>
            </div>
        </div>
        <button onclick="sendData()">send</button>
    </form>
    @section scripts{ 
    <script type="text/javascript">
        function sendData() {
            var count = 1;
            var formdata = {};
            formdata.Blurb = $('input[name="Blurb"]').val();
            formdata.SourceFile = $('input[name="SourceFile"]').val();
            var token = $('input[name="__RequestVerificationToken"]').val();
            $.post('/Submit/MediaAdd',
                { __RequestVerificationToken: token, model: formdata, count: count }
                );
        }
    </script>
    }
    

    result:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search