1

ASP MVC - C# - .NET 4.5 - Razor

Here is my view model:

public class PackageModel
{
    public List<Package> Packages { get; set; } 
}

Here is the class:

public class Package
{
    public string Name { get; set; }
    public string Description { get; set; }
    public int Qty { get; set; }
    public DateTime Received { get; set; }
}

On the page I have list of controls (textboxes, datepickers, etc). One for each element in the class "Package". Below these controls I have a button that will take the data populated in these controls and add them to a table below. Behind the scenes they are actually getting added to a JSON array. My question is that when I submit this form, how can I bind that JSON array of objects to the model "PackageModel" so it's available in the controller?

Any help is appreciated

UPDATE

Here is the mockup controller

[HttpPost]
public ActionResult SubmitPackage(IList<Package> Packages)
{
}

Here is a console log of the JSON being sent:

[{"Name":"Test","Description":"TestDesc","Qty":"1","Received":"12/12/2013"}] 

UPDATE2

Turns out I was just missing the defined content type in my jquery ajax call. Needed this line:

contentType: 'application/json; charset=utf-8'
Will
  • 989
  • 4
  • 19
  • 33
  • Probably so. If not, serialize a `PackageModel` to JSON, and modify the JSON you build to match, so that it can be deserialized as a `PackageModel`. (e.g. you might need to label your array as `"Packages"` and put it in its own object, instead of having it on its own) – Tim S. Sep 24 '13 at 19:56
  • If I understand correctly, you have the JSON array of objects in JavaScript and just want to POST it to a controller as a PackageModel? – Trevor Elliott Sep 24 '13 at 20:10
  • Possible duplicate ... http://stackoverflow.com/questions/13779043/post-json-array-to-mvc-controller – ramsey_tm Sep 24 '13 at 20:15
  • @Moozhe that is correct. However when I post the JSON back to the controller it says that the List has 0 records. – Will Sep 24 '13 at 21:05
  • @Slump yes it's very similar. I've modified my code to match the example in the link you've posted, but I'm getting a null for the model in the controller. – Will Sep 24 '13 at 21:27
  • Solved it, see Update 2. Thanks for everyone's help. – Will Sep 24 '13 at 21:31

0 Answers0