将数据从Html.Action传递到局部视图

时间:2013-01-20 02:05:53

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

我还是MVC 3的新手。我需要通过控制器将@ Html.Action方法的数据传递给局部视图。

所以这是我的流程。

我会像这样打电话给@ Html.Action:

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

然后它会击中我的控制器。这是我家庭控制器中的方法:

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>

但是:我得到了一个模型的空例外,这意味着它没有通过。

4 个答案:

答案 0 :(得分:5)

试试这个:

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

在SidebarMain Action中添加一个断点,看看是否有items

答案 1 :(得分:1)

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

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

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

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

答案 2 :(得分:0)

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功能,我为兔子的踪迹道歉:)

答案 3 :(得分:0)

DarthVader的建议可能有效。这就是我最终做的事情:

1)删除了控制器

2)这样称呼:

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

3)这是我的观看代码:

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