3

I am working with a MVC application and have ran into an issue when posting to a controller with a object of a class that inherits from another class. The base properties of the object are not being mapped correctly.

I Currently have the following class structure:

public class A
{
     public DateTime Property1;
     public DateTime Property2;
}

//Class B Inherits from A.
public class B : A
{
     public int[] intArray;
}

When I do my JQuery post of the Class B object in JSON, it only maps (or populates) the int[] intArray property, and does not seem to be able to populate Class A base properties.

In my ajax post, here is how my JSON.stringify data looks like.

[{"Property1": '10/21/2013', "Property2": '11/21/2013', "intArray": [1,2,3,4,5]}]

Jquery Ajax Post:

var dataObject = @(Html.Raw(new JavaScriptSerializer().Serialize(Model)));
dataObject= [{"Property1": '\/Date(0123131)\/', "Property2": '\/Date(0123131)\/', "intArray": [1,2,3,4,5]}];
dataObject= JSON.stringify(dataObject);

$.ajax(
{
url: '@Url.Action("GenerateExpensePeriod", "Expense")',
            data: dataObject,
            type: 'POST',
            contentType: 'application/json',
            success: function (results) {
                return results;
            },
            error: function (error) {
                alert('Error');
            }

        });

`

My controller method signature is:

public ActionResult ActionName(ClassB data)
{ }

The intArray property is the only property that gets populated. How would I get Property1 and Property2 populated?

Thanks.

tereško
  • 58,060
  • 25
  • 98
  • 150
nav
  • 509
  • 4
  • 19

2 Answers2

2

Seems like the Date was not being parsed correctly using the JavaScriptSerializer.

To Solve this I need to apply the following

dataObject["Property1"] = new Date(parseInt(dataObject["Property1"].substr(6)));

Has nothing to do with inheritance, as I was mistaken.

nav
  • 509
  • 4
  • 19
1

The problem is with how you serialize the model try using

var dataObject = { json : "@Html.Raw(JsonConvert.SerializeObject(Model))" };

See this stack post.

JSON.net Serialize C# object to JSON Issue

Community
  • 1
  • 1