1

I want to get the model during BindModel and cast it to a type specified in the bindingContext:

var reportFormTypeName = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".TableInputModelTypeName");

Type reportFormType = Type.GetType("MyNameSpace.ViewModels." + reportFormTypeName.AttemptedValue);

var model = (reportFormType)bindingContext.ModelMetadata.Model;

This wont work however - i'm guessing it's a simple reflection thing that i can't get my tired brain to sort out - anyone got any clues?

:)

2 Answers2

1

You need to instantiate it:

var reportFormTypeName = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".TableInputModelTypeName");
Type reportFormType = Type.GetType("MyNameSpace.ViewModels." + reportFormTypeName.AttemptedValue);
var model = Activator.CreateInstance(reportFormType);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • problem wuith that is that i don;t have the bindingContext.ModelMetadata.Model data in the model anymore –  Jun 26 '11 at 17:14
  • @iwayneo, what are you trying to do? – Darin Dimitrov Jun 26 '11 at 17:15
  • basically this: http://stackoverflow.com/questions/6484972/viewmodel-with-listbaseclass-and-editor-templates –  Jun 26 '11 at 17:16
  • my plan came from http://www.codinginstinct.com/2010/03/aspnet-mvc-and-convention-based-forms.html –  Jun 26 '11 at 17:18
  • @iwayneo, OK, I will then answer your original question as it is far more clear than this one. 5 secs please. – Darin Dimitrov Jun 26 '11 at 17:19
  • @iwayneo, answer posted: http://stackoverflow.com/questions/6484972/viewmodel-with-listbaseclass-and-editor-templates/6485552#6485552 – Darin Dimitrov Jun 26 '11 at 17:35
0

You can't do that. You're asking the compiler to work with a type that's known only at run time, which is simply not possible. If you know the type at compile time, just cast to it. If you don't, how do you expect to work with it?

svick
  • 236,525
  • 50
  • 385
  • 514
  • i'm not loving the hard coding and switching on strings but maybe this is the best way for now? –  Jun 26 '11 at 17:23
  • @iwayneo, maybe there is a better way, but you would have to ask a more concrete question, if we are to help you with that. What exactly are you trying to achieve? How does your code look like now? – svick Jun 26 '11 at 17:34