简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM