4

I am trying to post a form to the controller in which the controller accepts a FormCollection as a parameter. When I try to access an item within the dsCollection I get null. The only items within the FormCollection is "__RequestVerificationToken" and "dsCollection". Another thing is I am generating my forms HTML dynamically using javascript and assigning values to them at the same time.

Here is my ajax to post data to serverside:

$(document).ready(function () {
$('#postEditDatasource').click(function (event) {
    alert(JSON.stringify(deletedDatapoints));
    //serialise and assign json data to hidden field
    $('#dsDeletedDP').val(JSON.stringify(deletedDatapoints));

    //anti forgery token
    //get the form
    var form = $('#__dsAjaxAntiForgeryForm');
    //from the form get the antiforgerytoken
    var token = $('input[name="__RequestVerificationToken"]', form).val();

    var URL = '/Settings/EditDatasource';
    console.log(form);
    //we make an ajax call to the controller on click
    //because the controller has a AntiForgeryToken attribute
    //we need to get the token from the form and pass it with the ajax call.
    $('#__dsAjaxAntiForgeryForm').on('submit', function () {
        $.ajax({
            url: URL,
            data: {
                __RequestVerificationToken: token,
                dsCollection: form.serialize()
            },
            type: 'POST',
            success: function (result) {
                alert('this worked')
                if (data.result == "Error") {
                    ShowDatasourcePostAlert('failPost', 3000);
                } else {
                    ShowDatasourcePostAlert('successPost', 3000);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR + ', ' + textStatus + ', ' + errorThrown);
            }
        })
        return false;
    })
});
})

and here is my controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult EditDatasource(FormCollection dsCollection)
    {
        var devName = dsCollection["deviceName"];
            //LoadDataToViewModel();

            //Get the name of the device in which we will pass it to the XML edit helper 
            //In order for us to locate the
            //var getEditDatasource = Convert.ToString((from ds in dsVM.devices
            //                         where ds.deviceID == Convert.ToInt64(dsCollection["dsID"])
            //                         select ds.deviceName));


            return new EmptyResult();
    }

and here is a snippet of my HTML, I have too many controls but they pretty much follow the same formatting.

    <div class="form-group">
<label class="col-md-2 control-label" for="deviceName">Device Name: </label>
<div class="col-md-10">
<input id="deviceName" class="form-control" type="text" data-val="true" data-val-required="Device name is required" name="deviceName" value="TestName">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="deviceDisplay">Displayed As: </label>
<div class="col-md-10">
<input id="deviceDisplay" class="form-control" type="text" data-val="false" data-val-required="Device name is required" name="deviceDisplay" value="testDisplay">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="deviceDesc">Description: </label>
<div class="col-md-10">
<textarea id="deviceDesc" class="form-control" data-val="false" name="deviceDesc">Test desc</textarea>
</div>
</div>

If I use serializeArray() it gives me back 31 entries however the entries are "dsCollection[0][name]" "dsCollection[0][value]" with the index going all the way up to 30

4
  • Have you tried: api.jquery.com/serializeArray Commented Jun 30, 2015 at 15:52
  • You have a line that said console.log(form); is this result null? Commented Jun 30, 2015 at 15:53
  • @Luis.Andrade no it is not null Commented Jun 30, 2015 at 15:56
  • @Johnathon64 Yeah, something is happening I'm not sure what is it, I'm not an expert but I try to help. I recomend you to use this link helper because if you have a model it will write for you the ajax call and I think that you could send the token as a parameter Commented Jun 30, 2015 at 16:54

1 Answer 1

5

serialize method transform your form fields in a query string so you should just append the token to that string instead of creating another object.

If you inspect your request today you'll see that you're posting a value like this:

_RequestVerificationToken=token&dsCollection=deviceDesc%3Dcontent1%26deviceDisplay%3Dcontent2

When you have an antifogery token in a standard form, token data is sent alongside other input data (because actually it's just an hidden input) so the correct way to send it would be:

deviceDesc=content1&deviceDisplay=content2&_RequestVerificationToken=token

Other thing is, it looks like your anti forgery token is already inside your form so you do not need to do anything else than just form.serialize.

You can do the following in your javascript code:

data: form.serialize()
Sign up to request clarification or add additional context in comments.

1 Comment

does serialize also include hidden input fields? In my collection they do not seem to be included when I step through my C# code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.