ASP.NET MVC 4 部分视图无法工作

5

I wrote a partial method like this :

public ActionResult _StatePartial()
        {
            ViewBag.MyData = new string[] { "110", "24500" };
            return View();
        }

_Layout页面中渲染_StatePartial视图:

@Html.Partial("_StatePartial")

这是我的部分视图代码:
@{
    string[] Data = (string[])ViewBag.MyData;
}
<div id="UserState">
        Reputation: @Html.ActionLink(Data[0], "Reputation", "Profile") | 
        Cash: @Html.ActionLink(Data[1], "Index", "FinancialAccount")
</div>

但是当我运行这个项目时,_StatePartial方法没有被调用,ViewBag始终为null。
Server Error in '/' Application.
Object reference not set to an instance of an object. 

请注意,这些参数不是我的模型字段,而是通过调用Web服务方法计算得出的。但我会在我的问题中不断设置这些值。
我该怎么办? 有没有关于将参数传递给局部视图的想法? 谢谢。
2个回答

9

您的通话:

@Html.Partial("_StatePartial")

这将渲染视图,但不会调用操作。只有在您的父页面操作中设置所有视图数据时,才会使用此选项。在您的情况下,您需要使用以下内容:

@Html.Action("_StatePartial")

这将调用动作以检索和执行视图。

1

另外:

return View();

是用于返回带有布局的视图。您需要:

return PartialView();

我建议使用这个:

public ActionResult StatePartial()
{
    ViewBag.MyData = new string[] { "110", "24500" };
    return View("_StatePartial");
}

但最好使用强类型模型,而不是ViewBag


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接