Victor
Victor

Reputation: 5107

Convert string parameter to object type

Consider the following code:

public ActionResult GenericActionForSomething(string objectType)
    {
        switch (objectType)
        {
            case "Business":
                // Do Something with object here, like save
                _db.Create<Business>();
                break;
        }

        return View();
    }

How can I convert a string parameter to an object? For this example I need to convert the parameter "objectType" into an object of type "Business". Any ideas would be greatly appreciated.

Upvotes: 1

Views: 454

Answers (4)

Konamiman
Konamiman

Reputation: 50273

You can instantiate an object based on its type name by using Activator.CreateInstance. For that particular overload of the method you need to supply the assembly name as well; for this you may find useful the Assembly class' GetExecutingAssembly and GetCallingAssembly methods.

Upvotes: 2

viky
viky

Reputation: 17659

You need to use reflection to achieve this. You can either use Activator.CreateInstance(className) method or you can first load the Assemply containing your type and then call CreateInstance() method like this:

Assembly assem = Assembly.Load(assemblyName);
Object obj = assem.CreateInstance(className);

Upvotes: 0

James Kolpack
James Kolpack

Reputation: 9382

I'm thinking that you might be wanting to do model binding to your action, like:

public ViewResult NewBusiness(Business business)
{
    _db.Create<Business>(business);
    return View();
}

Read a general overview of model binding in this article.

Upvotes: 0

Anton Gogolev
Anton Gogolev

Reputation: 115691

There's no one single way to do this. If your Business class has a constructor which accepts string, you can invoke that. If it has an explicit conversion operator, you can use it as well. If it has an associated TypeConverter, use that too.

Your question is way too broad.

Upvotes: 0

Related Questions