将模型映射到控制器内的ViewModel

时间:2016-10-31 10:36:25

标签: c# asp.net-mvc viewmodel

我正在尝试将模型转换为控制器内的viewmodel,我需要使用@ Html.DropdownListFor()内部的数据。我的观点是使用viewmodel所以我需要先将所有模型数据映射到此viewmodel

模型 StandardSubjectAreaTierOne

public class StandardSubjectAreaTierOne
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Sector> Sectors { get; set; }
}

模型 扇区

public class Sector
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ApprenticeshipOccupationId { get; set; }
    public IEnumerable<Standard> Standards { get; set; }
}

型号 标准

public class Standard
{
    public int Id { get; set; }
    public int ApprenticeshipSectorId { get; set; }
    public string Name { get; set; }
    public ApprenticeshipLevel ApprenticeshipLevel { get; set; }
}

ViewModel StandardViewModel

public class StandardViewModel
{
    public int Id { get; set; }

    public int ApprenticeshipSectorId { get; set; }

    public SelectList ApprenticeshipSectors { get; set; }

    public string Name { get; set; }

    public SelectList ApprenticeshipLevels { get; set; }

    public string ApprenticeshipLevel { get; set; }
}

我不完全确定我是否可以使用SelectList作为我的下拉列表。

控制器:

[HttpGet]
public ActionResult CreateStandard()
{
    var response = _adminMediator.GetStandard();

    return View(response.ViewModel);
}

_adminMediator.GetStandard返回

MediatorResponse<List<StandardSubjectAreaTierOne>>

响应需要转换为viewmodel,因为我收到一条错误,说StandardSubjectAreaTierOne无法转换为StandardViewModel

查看

@model SFA.Apprenticeships.Web.Raa.Common.ViewModels.Admin.StandardViewModel

@Html.DropDownListFor(m => m.ApprenticeshipLevel, Model.ApprenticeshipLevels)

新控制器:

[HttpGet]
public ActionResult CreateStandard()
{
    var response = _adminMediator.GetStandard();

    var test = response.ViewModel.SelectMany(
                r =>
                    r.Sectors.SelectMany(
                        ss =>
                            ss.Standards.Select(
                                s =>
                                    new StandardViewModel()
                                    {
                                        ApprenticeshipLevel = s.ApprenticeshipLevel,
                                        ApprenticeshipSectorId = ss.Id,
                                    }))).ToList();

    return View(test);
}

我还将视图中的模型更改为

List<SFA.Apprenticeships.Web.Raa.Common.ViewModels.Admin.StandardViewModel>

现在,当我运行应用程序

时,我的下拉列表出现问题

0 个答案:

没有答案