创建具有更多局部视图和不同模型的视图

Create a View with more Partial View and different model

我想要一个与选项卡 jQuery 一起使用的视图,它允许我填充多个表(使用局部视图)。基本上我希望能够用一个视图填充数据库的表。

我的模型示例:

public class Tag
{
    public int Id { get; set; }
    public string Tag { get; set; }
    public string Note { get; set; }
}

public class City
{
    public int Id { get; set; }
    public string City { get; set; }
    public string Note { get; set; }
}

我的控制器:

public class tabController : Controller
{
    public ActionResult tab()
    {
        var tvm = new MyDbContext();
        return View(tvm);
    }
}

我的观点:

@model ??????????

@section Scripts {
    <script>
        $(function () {
            $("#tabs").tabs();
        });
   </script>
}

<div id="tabs">
    <ul>
        <li><a href="#tabs-1">tag</a></li>
        <li><a href="#tabs-2">city</a></li>
        <li><a href="#tabs-3">country</a></li>
        <li><a href="#tabs-4">more more</a></li>
    </ul>
    <div id="tabs-1">
        <div class="panel-body">
            @Html.Partial("_tag", ????? )
        </div>
    </div>
    <div id="tabs-2">
        <div class="panel-body">
            @Html.Partial("_city", Model?)

        </div>
    </div>
    <div id="tabs-3">
        <div class="panel-body">
            @Html.Partial("_country", @Model.Country)
        </div>
    </div>
    <div id="tabs-4">
        <div class="panel-body">
            @Html.Partial("_note"@*, @Model.NoteShares*@)
        </div>
    </div>
</div>

我看到错误:

The model item passed into the dictionary is of type 'myprojMVC5.Models.tabs', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[myprojMVC5.Models.tabsl]

选项 1:查看模型

创建包含要显示的集合属性的视图模型

public class TabsVM
{
  public IEnumerable<Tag> Tags { get; set; }
  public IEnumerable<City> Cities { get; set; }
}

然后在控制器中,初始化视图模型的实例并填充 te 集合

public class tabController : Controller
{
  public ActionResult tab()
  {
    var tvm = new MyDbContext();
    TabsVM model = new TabsVM()
    {
      Tabs = tvm .Tabs(),
      Cities = tvm.Citys()
    }
    return View(model);
}

并在视图中

@model yourAssembly.TabsVM
....
@Html.Partial("_tag", Model.Tags)
....
@Html.Partial("_tag", Model.Cities)

选项 2:仅调用 return 部分视图

的子操作方法
[ChildActionOnly]
public ActionResult FetchTags()
{
  var tvm = new MyDbContext();
  var model = tvm.Tags();
  return PartialView("_tags", model);
}

并且在视图中(不需要将模型传递给视图)

....
@Html.Action("FetchTags") // assumes the methods will be in the same controller
....
@Html.Action("FetchCities") // or you can use @{ Html.RenderAction("FetchCities"); }