Search code examples
c#asp.net-mvcformcollection

Convert FormCollection to object of type known only at runtime


I have controller with action containing code, which looks like

public ActionResult Index(FormCollection data)
{
    var type = findTypeByName(data["CastToTypeName"]);
    var model = transformRequestDataToType(data/* or may be Request*/, type) as DbEntity;
    SaveData(model);
    ...
}

Is there any way to transform request data to object of runtime-known type? I post data to controller with <form> and trying to find solution without changing form data to json.


Solution

  • First of all, I simplified input names notation to such as:

    a.name
    a.items\
    a.items/name
    a.items/desc
    a.items\
    a.items/name
    a.items/desc
    

    was

    a.name
    a.items.Index
    a.items[0].name
    a.items[0].desc
    a.items.Index
    a.items[1].name
    a.items[1].desc
    

    next I extract form data before submit using js, prevent form submit and send ajax post request with the form data to url defined in action form attribute. On server side I parse data and recursively assign it to properties of instance of given type. So I can ParseAs<MyType>(Request) or even ParseAsGiven(Request) when CastToTypeName value is set.