如何将ViewModel列表传递给View?

问题描述 投票:0回答:2

我是C#和asp.net mvc的新手,我一直试图在这里和其他论坛找到我的问题的答案,但没有成功。但是,如果在此之前已经提出并回答了这个问题,那么我很抱歉,请您链接到该帖子。

我正在尝试创建一个树视图,我将ViewModel列表传递给我的View。

我使用代码优先方法,并在我的模型和数据库之间添加了迁移。

我的问题是如何将ViewModel的对象列表传递给View?我可以从控制器传递模型的对象列表,但是如何传递ViewModel的对象列表?那可能吗?

也许有一个简单的解决方案,我还没有找到,也许我这样做是错的。无论如何,我真的需要一些帮助。

public class MyClass
  {
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Name { get; set; }
  }


public class MyClassViewModel
  {
    public MyClass Parent { get; set; }
    public List<MyClass> Children
    {
        get { return GetChildren(); }
    }
    public List<MyClass> GetChildren()
    {
        var listOfChildren = new List<MyClass>().Where(c => c.ParentId == 
        Parent.Id).ToList();

        return listOfChildren;
    }
  }


public ActionResult CreateTree()
    {
        var viewModel = new MyClassViewModel();
 //This only returns one instance of an object, how to return a list?
        return View("CreateTree", viewModel); 
    }
c# asp.net-mvc viewmodel
2个回答
0
投票

这很简单,您只需将视图模型列表传递给视图:

[HttpGet()]
public IActionResult CreateTree()
{
    List<MyViewModel> viewModelList = MyViewModel.GetList();
    return View("CreateTree", viewModelList);
}

在视图上,您​​可以通过@model指令设置模型的预期类型。

@model List<MyViewModel>
@{
    //stuff
}

现在,您可以遍历您的viewmodel列表。

@foreach (MyViewModel item in Model)
{
     //stuff
}

0
投票

您可以创建一个包含ViewModel列表的类

public class ModelWithListOfViewModels
{
    public List<ViewModel> ViewModels { get; set; }
}

将ViewModel添加到控制器的列表中

public ModelWithListOfViewModels model { get; set; }

[HttpGet()]
public ActionResult FillList()
{
    model = new ModelWithListOfViewModels();
    //Here you fill the list with the ViewModels you want to pass to the View
    model.ViewModels.Add(/** ViewModel here **/);
    return View("CreateTree", model);
}

然后只需循环遍历列表即可在View中获取模型

@model ModelWithListOfViewModels

@foreach (var vm in Model.ViewModels)
{
     //use vm to get access to a ViewModel added in the list
}
© www.soinside.com 2019 - 2024. All rights reserved.