maztt
maztt

Reputation: 12294

asp.net mvc using typeof convert derived type to base type

   public ActionResult CreateAdminItemsViewModel(int Typeid, int FormId)  
    {
        ViewBag.formid = FormId;


       Type myType1 = Type.GetType("RadioButtonListViewModel");

        BaseViewModel c= myType1; // doesn't work

        return PartialView("CreateAdminItemsViewModel", instantiationType);
    }

How can i make this code work? how can i assign my derived type passed from the view to my base view class

Upvotes: 0

Views: 196

Answers (2)

Gian Paolo
Gian Paolo

Reputation: 4249

With these:

Type myType1 = Type.GetType("RadioButtonListViewModel");
BaseViewModel c= myType1; // doesn't work

You are getting at runtime a Type object and then try to assing it to a BaseViewModel refererence: this cleary is wrong.

If you want to assign an instance of RadioButtonListViewModel, you can use Activator

BaseViewModel c = (BaseViewModel)Activator.CreateInstance(myType1);

I assume your code is just a semplified version of the real one. If not, you obviusly can use a simple new:

BaseViewModel c = new RadioButtonListViewModel();

Upvotes: 1

Alireza
Alireza

Reputation: 5503

If I've understood the problem correctly, you need to create an instance of the class RadioButtonListViewModel and assign it to a variable of type BaseViewModel which is its base class. To create an isntance of type myType1, you can use

var c = Activator.CreateInstance(myType1) as BaseViewModel;

Upvotes: 1

Related Questions