Reputation: 444
I have a view with an HTML table, where the rows are created dynamically. What is the best way to send the table data to the controller & update the model? Currently, I have converted the table to JSON, as shown below:
{"0": ["Job Code","Hours","Rate","Expense"],"1": ["a1","b1","c1","d1"],"2": ["a2","b2","c2","d2"]}
I tried to use the newtonsoft JSON deserialize method, but it failed.
I think it failed to convert this format of JSON.
Is there any other method to serialize table that is accepted by newtonsoft JSON?
Upvotes: 1
Views: 2763
Reputation: 719
The {} in JSON tells the de-serializer that it is going to create an object. Keeping this in mind, the JSON you created would make a single object - with each property containing an array of strings. It seems like you want a list of objects, rather than this.
Are you using this method to de-serialize?
JsonConvert.DeserializeObject<T>(json)
You need to provide a type to de-serialize to. So in this case it would be:
class JobDetails
{
public string JobCode { get; set; }
public double Hours { get; set; }
public double Rate { get; set; }
public double Expense { get; set; }
}
In order to de-serialize to this type your JSON.NET JsonConvert call would look like:
[HttpPost]
public ActionResult Testing(string json)
{
var list = JsonConvert.DeserializeObject<List<JobDetails>>(json)
UPDATE_YOUR_MODEL_HERE(list);
return WHAT_YOU_WANT_TO_RETURN_HERE;
}
Your JSON would look like:
[
{
"JobCode": "a1",
"Hours": 37.5,
"Rate": 10,
"Expense": 375
},
{
"JobCode": "a2",
"Hours": 10,
"Rate": 20,
"Expense": 200
},
{
"JobCode": "a3",
"Hours": 37.5,
"Rate": 20,
"Expense": 750
}
]
This will convert the JSON into a List of JobDetails objects.
Alternatively if you want to resolve the JSON to objects as an Action parameter this should do the trick:
[HttpPost]
public ActionResult Testing(List<JobDetails> list)
{
UPDATE_YOUR_MODEL_HERE(list);
return WHAT_YOU_WANT_TO_RETURN_HERE;
}
If you're having trouble getting your table serialized to correct JSON try looking at this jQuery plug-in: https://github.com/lightswitch05/table-to-json
Upvotes: 1