切换控制器内的视图模型

时间:2016-08-25 11:23:01

标签: c# asp.net-mvc mvvm controller viewmodel

让我们说,我有多种类别,如主板,机箱和驱动器。他们每个人都有自己的viewmodel视图,比如MotherboardsView,CasesView和DrivesView。和viewmodels - MotherboardsViewModel,CasesViewModel和DrivesModel。 我有控制器,我想根据类别切换视图模型。 抽象代码看起来像这样:

//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)
}

有可能,我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:1)

这是一个基本的编程概念,与MVC无关。必须在使用它的代码的“范围”内声明变量。您的viewmodel在switch语句中声明,并且在该代码块之外无法看到。试试这个声明viewmodel,以便方法中的任何代码都可以访问它。注意var已被删除。

//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)
}