【问题标题】:Passing data from Html.Action to the partial view将数据从 Html.Action 传递到局部视图
【发布时间】:2013-01-20 02:05:53
【问题描述】:

我对 MVC 3 还比较陌生。我需要通过控制器将数据从我的 @Html.Action 方法传递到局部视图。

这是我的流程。

我会这样调用@Html.Action:

@Html.Action("SidebarMain", "Home", new List<int>(new int[] {1, 2, 3}))

然后它会击中我的控制器。这是我在 Home Controller 中的方法:

public ActionResult SidebarMain(List<int> items)
{
    return View(items);
}

那么我的部分视图应该能够像这样访问数据:

@model List<int>

@{
    ViewBag.Title = "SidebarMain";
    Layout = null;
}

<div>
@foreach (int item in Model)
{
    <div>@item</div>
}
</div>

但是:我收到模型的空异常,这意味着它没有通过。

【问题讨论】:

  • 为什么不加评论就投反对票?

标签: c# asp.net .net asp.net-mvc-3 asp.net-mvc-3-areas


【解决方案1】:

试试这个:

Html.Action("SidebarMain", "Home", new { items = new List<int>(new int[] {1, 2, 3}) })

然后在你的 SidebarMain Action 中设置一个断点来查看,如果你得到items

【讨论】:

    【解决方案2】:

    简而言之:您的代码缺少 Html.Action() 中的 items 参数名称。 除此之外,代码应该是功能性的。

    Html.Action("SidebarMain", "Home", new {items = new List<int>(new int[] {1, 2, 3}) })
    

    作为建议的做法,在我看来,我会使用专用的ViewModel,而不仅仅是发送整数数组。因为,通过这种干净的ViewModel - 您在视图中显示的属性的容器,您的代码可能会在以后添加其他属性,因为我们的代码总是在发展。

    ViewModel 概念的使用参考:Exercise 5: Creating a View Model

    【讨论】:

    • 澄清一下,ViewModel 是指视图被强类型化的模型正确吗?
    • 是的,你是对的,我的第二段试图澄清/提到这一点。
    • 哇,谢谢。我没有意识到视图中的参数名称必须与控制器中的相同。
    【解决方案3】:

    DarthVader 的回答很好。您是否将其作为 Ajax 返回?如果你将它嵌入到主视图中,你应该真正将它作为 PartialView 返回

    return PartialView("SidebarMain", model);
    

    这就是 SidebarMain 是您要返回的局部视图的名称。结合 DarthVader 的建议尝试此操作,并确保您获得了一个模型以传回视图。

    发布后,我意识到您正在使用 Html.Action。如果这是一个真正的侧边栏,它应该加载 ajax 作为局部视图,你应该调用

    Ajax.ActionLink("SidebarMain", "Home", new { items = new List<int>(new int[] {1, 2, 3}) })
    

    这将允许您停留在当前页面上。如果您不是在寻找 ajax 功能,我为兔子足迹道歉 :)

    【讨论】:

      【解决方案4】:

      DarthVader 的建议可能奏效了。这就是我最终要做的:

      1) 移除控制器

      2) 这样称呼它:

      @{Html.RenderPartial("SidebarMain", new int[] {1,3,4,2});}
      

      3) 这是我的视图代码:

      @model int[]
      @foreach( int item in Model){
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-14
        • 1970-01-01
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多