Aaron Aaron - 3 months ago 34
C# Question

Switching viewmodel inside controller

Lets tell, i have multible categories, like motherboards, cases, and drives. Each of them have their own view with viewmodel, something like MotherboardsView, CasesView and DrivesView. And viewmodels - MotherboardsViewModel, CasesViewModel and DrivesModel.
I have controller where i wanna switch viewmodels based on category.
Abstract code would look something like this :


//GET Action
public ActionResult Create(string Category)
{
switch (Category)
{
case "Motherboards":
var viewModel = new MotherboardsViewModel { };
break;
case "Cases":
var viewModel = new CasesViewModel { };
break;
default:
var viewModel = new DrivesViewModel { };
break;
}

//Here i use switched viewmodel to change some values, like:
viewModel.Name = GetRandomName();
...

//And i return view and viewmodel
return View(Category + "View", viewmodel)
}


Is it possible, and how could i solve this problem?

Answer

This is a basic programming concept, not specifically related to MVC. Variables must be declared within "scope" of code that uses it. Your viewmodel is declared within the switch statement and cannot be seen outside of that code block. Try this which declares viewmodel such that it can be accessed by any code in the method. Notice var has been removed.

//GET Action
public ActionResult Create(string Category)
{
    object viewmodel = null;

    switch (Category)
    {
        case "Motherboards":

            MotherboardviewModel = new MotherboardsViewModel { };
            //Here i use switched viewmodel to change some values, like:
            MotherboardviewModel.Name = GetRandomName();
            ...
            viewModel = MotherboardviewModel;

            break;
        case "Cases":

            CaseviewModel = new CasesViewModel { };
            //Here i use switched viewmodel to change some values, like:
            CaseviewModel.Name = GetRandomName();
            ...
            viewModel = CasesviewModel;

            break;
        default:

            DriveviewModel = new DrivesViewModel { };
            //Here i use switched viewmodel to change some values, like:
            DriveviewModel.Name = GetRandomName();
            ...
            viewModel = DriveviewModel;

            break;
    }

    //And i return view and viewmodel
    return View(Category + "View", viewmodel)
}
Comments