Submitting JSON data to MVC controller. Why does it not handle complex types?
-
11-11-2019 - |
Question
Define C# helper classes as:
`
public class SelectedFiles
{
public string Host { get; set; }
public List<SelectedFile> Files { get; set; }
}
public class SelectedFile
{
public string ShortName {get; set;}
public string Category { get; set; }
}`
And let define two controller methods (+ Deserialize helper):
private SelectedFiles Deserialize(string json)
{
using (MemoryStream stream = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SelectedFiles));
return (SelectedFiles) serializer.ReadObject(stream);
}
}
/// <summary>
/// MVC seems to be incapable to deserizalize complex types.
/// </summary>
/// <param name="selectedFilesJSON"></param>
/// <returns></returns>
public void UploadFiles(SelectedFiles selectedFilesJSON)
{
var result = selectedFilesJSON;
}
/// <summary>
/// </summary>
/// <param name="selectedFilesJSON"></param>
/// <returns></returns>
public void UploadFilesJSON(string selectedFilesJSON)
{
if (!string.IsNullOrEmpty(selectedFilesJSON))
{
var result = this.Deserialize(selectedFilesJSON);
}
}
With javascript calling
var SelectedFiles = [];
var SelectedFile;
selectedCheckBoxes.each(function(idx, element){
SelectedFile = {ShortName: element.value, Category: "a category"};
SelectedFiles.push(SelectedFile);
});
var selectedFileMessage = {};
selectedFileMessage.Host = "test"
selectedFileMessage.Files = SelectedFiles;
var message = $.toJSON(selectedFileMessage);
$.ajax({url:"UploadFilesJSON", type:'POST', traditional:true, data: { selectedFilesJSON : message } , success: function(result){ alert(result);} });
$.ajax({url:"UploadFiles", type:'POST', traditional:true, data: { selectedFilesJSON : selectedFileMessage } , success: function(result){ alert(result);} });
The first .ajax POST method will work. Basically dumping the serialized JSON object as a string to the controller method.
The second .ajax POST does not work. It does not seems to figure out how to deserialize the 'SelectedFiles' helper class from the argument list.
One word: 'Flabergasted'
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow