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.

2
  • 1
    Add your jquery & json forming code too.. Commented Nov 15, 2013 at 15:58
  • Ok, let me edit my post. Commented Nov 15, 2013 at 15:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.