c# - Create an instance of an unknown type of object and TryUpdateModel -


i'm using mvc , have controller action handles several different view models, each view model has validation , i'd controller check validation.

this controller action:

[acceptverbs(httpverbs.post)] public actionresult wizardcaseresult(formcollection fc) {     viewa vm = new viewa();     tryupdatemodel<viewa>(vm); } 

how change code type of view model can set dynamically this:

[acceptverbs(httpverbs.post)] public actionresult wizardcaseresult(formcollection fc, string viewtype) {     viewtype vm = new viewtype();     tryupdatemodel<viewtype>(vm); } 

i have many different view models different action each type out of question.

you need write custom model binder work:

public class mymodelbinder : defaultmodelbinder {     protected override object createmodel(controllercontext controllercontext, modelbindingcontext bindingcontext, type modeltype)     {         var typevalue = bindingcontext.valueprovider.getvalue("viewtype");         var type = type.gettype(             (string)typevalue.convertto(typeof(string)),              true         );         var model = activator.createinstance(type);         bindingcontext.modelmetadata = modelmetadataproviders.current.getmetadatafortype(() => model, type);         return model;     } } 

and then:

[acceptverbs(httpverbs.post)] public actionresult wizardcaseresult([modelbinder(typeof(mymodelbinder))]object model) {     ... } 

now have ensure form sends viewtype parameter point view model want instantiate.

oh, , can forget strong typing such following when dealing types known @ runtime:

viewtype vm = new viewtype(); tryupdatemodel<viewtype>(vm); 

you might find following answer helpful.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -