Base class: AbstractBuildBlock, Derived: TextBlock, ImageBlock, EmptyBlock, ... .
Blocks here: Site -> Pages[someIndex] -> Rows[someIndex] -> BuildBlocks
Fields BuildBlocks is of type AbstractBuildBlock, so when I'm saving Site to DB in BuildBlocks each record has descriminator AbstractBuildBlock. I try to do the next in BuildBlockRepository:
switch(obj.ContentType)
{
case "text":
obj = obj as TextBlock;
context.BuildBlocks.Add(obj);
break;
}
After obj = obj as TextBlock
obj
is null
. The reason is that obj is of type AbstractBuildBlock. I found at msdn that this code should work:
BaseClass a = new DerivedClass()
DerivedClass b = a as DerivedClass
So I need reproduce this code at model binding. This is ajax request:
$('.saveSite').click(function () {
$.ajax({
url: '/Site/Update',
data: { site: getSite() },
method: 'POST',
success: function (data) {
console.log('Success save');
},
error: function (data) {
debugBox(data);
}
});
});
and mvc action for this request
public string Update(Site site)
{
siteRepository.Add(site);
return "Success";
}
So I send Site in json form, BuildBlocks that are in this site in form of json too, but of course their(blocks) type is not AbstractBuildBlock, they are all of TextBlock, ImageBlock, etc. and have fields with values.
The problem: Site has field BuildBlocks which type is AbstractBuildBlock and model binder do something like this:
buildBlock = new AbstractBuildBlock(); //loose derived classes fields and posibility to convert it in DerivedClass
buildBlocks.push(buildBlock)
but I need someting like this
switch(buildBlock.contenType) {
case "text" : buildBlock = new TextBlock();buidlBlocks.push(buildBlock);
}