Reputation: 365
In my MVC application, I have defined a ViewModel like:
public class TestModel : Test
{
public TestModel (Models.Test1 t1)
:base(t1)
{ }
public TestModel (Models.Test1 t1, Models.Test1 t2)
:base(t1,t2)
{ }
Class Test is defined as:
public class Test
{
public Test(Models.Test1 t1)
{
//set the properties for t1
}
public Test(Models.Test1 t1, Models.Test1 t2)
:this(t1)
{
//set properties for t2
}
}
// properties for t1 and t2
}
TestModel is used in my View to display combined fields from t1 and t2. When I submit the form like this:
$('form').submit(function (evt) {
Save($(this).serialize(),
function () {
$('.loading').show();
},
function () {
alert('success');
});
});
$('a.save').click(function (evt) {
$(this).parents('form').submit();
});
- the controller action below is never hit.
[HttpPost]
public JsonResult Save(TestModel camp)
{
Helper.Save(camp);
return Json(JsonEnvelope.Success());
}
I think the serialization is not working because TestModel derives from Test. Any suggestions on how to get this working?
Upvotes: 0
Views: 128
Reputation: 1038720
I think the serialization is not working because TestModel derives from Test. Any suggestions on how to get this working?
The serialization doesn't work because your TestModel
doesn't have a parameterless constructor. The default model binder doesn't know how to instantiate this class. Only classes with parameterless constructors should be used as view models. Or you will have to write a custom model binder to indicate which of the 2 custom constructors to use.
So go ahead and rethink your design of view models. It's OK to use inheritance but no custom constructors.
Upvotes: 1