0

I have the following script

$(function () {
                $("#btnConfirmParticipants").click(function () {
                    var jsonArray = [];               
                    $(".participantForm").each(function () {
                        jsonArray.push({ Name: ($(this).find("#Name").val()), Surname: ($(this).find("#Surname").val()), BirthDate: ($(this).find("#BirthDate").val()) });
                    });
                    var data = {
                        participants: JSON.stringify(jsonArray),
                        houseName: $('select[name="SelectedHousesParticipants"]').val(),
                        __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
                    };
                    $.ajax({
                        type: "POST",
                        url: "/ClientReservations/ChangeHouseParticipants",
                        data: data,
                        contentType: "application/json; charset=utf-8",
                        success: function (response) {

                        },
                    });
                });
            });

This script calls the method in controller

[HttpPost]
        [Authorize(Roles ="Klient")]
        public ActionResult ChangeHouseParticipants(List<Participant> participants,string houseName)
        {
            return View();
        }

When during execution I receive Invalid JSON primitives. Any proposals how to solve it?

Additionaly using partial views to display each essential fields for every Participant Partial View for all Participants

<div>
        @foreach (Participant item in Model)
        {
            <div >
                @Html.Partial("~/Views/Shared/_HouseParticipant.cshtml", item)
            </div>

        }
</div>

Partial view of single Participant

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal participantForm">
        <h4>Uczestnik</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" } )
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { id = "Name", htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Surname, new { id = "Surname", htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BirthDate, new { id = "BirthDate", htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>

    </div>
}
  • `participants: JSON.stringify(jsonArray),` -> `participants: jsonArray,` – Rory McCrossan Aug 23 '17 at 10:54
  • 1
    It needs to be `participants: jsonArray,` and then you stringify it all - `var data = JSON.stringify({ .... });` –  Aug 23 '17 at 10:54
  • But you need to add the token to `headers` (it will not work if its in the body when its been stringified). although your method does not have `[ValidateAntoForgeryToken]` so its not really necessary anyway –  Aug 23 '17 at 10:55
  • 1
    You code also means that you have invalid html (duplicate `id` attributes) and that you are not generating your form correctly in the first place. If you were, it would be as simple as `data: $('form').serialize()` without the `conntentType` option, so I suggest you need to fix that first. It also make no sense that you have `return View();` in your method. –  Aug 23 '17 at 10:58
  • I have posted PartialViews there are fileds that needs to be filled, so using a few same PartialViews for Participants makes that I have duplicated IDs? –  Aug 23 '17 at 11:08
  • @StephenMuecke I applied your suggestion about var data = JSON.stringfy({}) and it works fine. –  Aug 23 '17 at 11:10
  • Do NOT use partial views. Refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) to understand how to generate a view for a collection. But what is the point of making an ajax call in your case? (and if you did need to then its just `data: $('form').serialize();` and remove the `contentType` option –  Aug 23 '17 at 11:10
  • I select house by name then it opens formular with essential quantity of rows, I type info and confirm it by using ajax which call method controller. Then in object from Session I save typed data. –  Aug 23 '17 at 11:13
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/152629/discussion-between-stephen-muecke-and-contador6). –  Aug 23 '17 at 11:14

1 Answers1

0

Instead of

var data = {
  participants: JSON.stringify(jsonArray),
  houseName: $('select[name="SelectedHousesParticipants"]').val(),
  __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};

do

var data = {
  participants: jsonArray,
  houseName: $('select[name="SelectedHousesParticipants"]').val(),
  __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};
var jsonData = JSON.stringify(data);

and then pass jsonData in request.

anteAdamovic
  • 1,462
  • 12
  • 23