2

I am trying to post a full form and a separate list of strings to my controller. The form binds to the model but the list of strings doesn't bind to the list of strings in the controller and shows as a single string in a list.

var List = "one,two,three";
var dataToPost = $('#Form').serialize() + "&Words=" + JSON.stringify(List);
$.ajax({
   type: "POST",
   url: '/Home/Open/',            
   data: dataToPost,
   dataType: "json",
   success: function () {
      alert('ok');
   },
   error: function () {
      alert('error');
   }
});

Here is my MVC controller action:

[HttpPost]
public IActionResult Open(DataModel Model, List<string> Words)
{
   return View(Model);
}
5
  • You're combining two content types - url-encoded and JSON...the model binder can't deal with that. Why not just make this list part of the main model class anyway? Commented Apr 17, 2019 at 22:45
  • The list content is dynamically built on the client before they exist in the model. This was the only way I found to update the model in this regard as I couldn't see an easy way which would bind to the list in the model unless I am missing something. Commented Apr 18, 2019 at 6:12
  • Yes, the main one being: don't use JSON within an otherwise url-encoded set of data. It will just be seen as a string, not a list. The server does not know you made it into JSON. You need to use one data format throughout all the data you send in the request. And you can still have a placeholder property in the model ready to receive it....there's no need for it to be a separate input to the method as far as I can see Commented Apr 18, 2019 at 6:39
  • @ADyson can you explain how please. Is this a case of 'pushing' the list in Javascript to the serialised form? Commented Apr 18, 2019 at 8:09
  • You'd have to convert your JS List array to a URL-encoded string before appending it to the dataToPost. Maybe something like in the answers here stackoverflow.com/questions/26717228/… will help you Commented Apr 18, 2019 at 8:49

2 Answers 2

4

This works fine for me:

var List = ["one", "two", "three"];
var dataToPost = $('#Form').serializeArray();
List.forEach(function (value, index) {
    dataToPost.push({ name: 'Words[]', value: value });
});
Sign up to request clarification or add additional context in comments.

4 Comments

I changed the list formatting but the variable still only shows a single element in the controller variable: [0] = "[\"one\",\"two\",\"three\"]"
can you please also share the code of you MVC controller?
I have updated the main question with the MVC action code,
Ok, I also update my answer based on your feedback, and now this should bind to a list on Words on server side.
0

Please try the below code i have just modify your AJAX call.

var List = "one,two,three";
    var dataToPost = $('#Form').serialize();
    $.ajax({
        type: "POST",
        url: '/Home/Open/',
        data: { fx: dataToPost, Words: List },
        dataType: "json",
        success: function () {
            alert('ok');
        },
        error: function () {
            alert('error');
        }
    });

change controller code to below

 [HttpPost]
    public IActionResult Open(FormCollection fx, string Words)
    { 
    var lstWords = Words.Split(',').ToList();
        var val = fx["elementname"]//here you can pass input element name to get value
       return View(Model);
    }

3 Comments

I tried this but the Model becomes null and the List still contains the single string.
What is your DataModel ? if possible change DataModel to formcollection and then extract values from FormCollection.
I know this is a simple conversion on the controller end, just wanted to know if it was possible to take advantage automatic binding. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.