MVC3 - 将数据传递到局部视图的模型之外

37
有没有办法在将模型传递给Partial视图的同时传递一些额外的数据?
例如: @Html.Partial("_SomeTable", (List<CustomTable>)ViewBag.Table); 这是我现在拥有的。我能否添加其他内容而不更改我的模型? @Html.Partial("_SomeTable", (List<CustomTable>)ViewBag.Table, "TemporaryTable"); 我看到ViewDataDictionary作为参数。我不确定这个对象的作用或者它是否符合我的需求。
5个回答

66

ViewDataDictionary可以用来替换部分视图中的ViewData字典... 如果您没有传递ViewDataDictionary参数,则部分视图的viewdata与其父视图相同。

如何在父视图中使用它的示例:

@Html.Partial("_SomeTable", (List<CustomTable>)ViewBag.Table, new ViewDataDictionary {{ "Key", obj }});

然后在局部视图中,您可以按如下方式访问此对象:

@{ var obj = ViewData["key"]; }

完全不同的方法是使用Tuple类将原始模型和额外数据分组,如下所示:

@Html.Partial("_SomeTable", Tuple.Create<List<CustomTable>, string>((List<CustomTable>)ViewBag.Table, "Extra data"));

那么这个部分的模型类型将是:

@model Tuple<List<CustomTable>, string>

Model.Item1 返回列表对象,Model.Item2 返回字符串。


2
我无法理解 new ViewDataDictionary {{ "Key", obj }} 中的语法。 new ViewDataDictionary() 中的括号在哪里? - Mahmood Dehghan
2
当你有一个对象初始化器时,它们就是多余的...这就是代码直接在新的ViewDataDictionary之后的情况...请参阅http://msdn.microsoft.com/en-us/library/bb531208.aspx。 - Martin Booth
1
@{ var obj = ViewBag.Key; } 也可以用来访问传递的数据。 - MEC

7
您应该能够将其放入ViewBag中,然后从部分视图中的ViewBag访问它。 请参阅此SO答案

6
我也遇到了这个问题。我想要将一小段代码复制多次,但不想复制粘贴。代码会略有不同。在查看其他答案后,我不想走那条路,而是决定使用一个简单的Dictionary
例如: parent.cshtml
@{
 var args = new Dictionary<string,string>();
 args["redirectController"] = "Admin";
 args["redirectAction"] = "User";
}
@Html.Partial("_childPartial",args)

_childPartial.cshtml

@model Dictionary<string,string>
<div>@Model["redirectController"]</div>
<div>@Model["redirectAction"]</div>

3

您可以像Craig Stuntz在这里演示的那样变得更加聪明

Html.RenderPartial("SomePartialView", null, 
    new ViewDataDictionary(new ViewDataDictionary() { {"SomeDisplayParameter", true }})
        { Model = MyModelObject });

0
如果你想将当前的ViewData内容追加到一个新的字典条目中,以便传递给一个部分视图,你可以这样做。
@Html.Partial("_somepartial", Model,  new ViewDataDictionary (ViewData) { { "Name", "John" }, { "Surname", "Doe" } })

注意在ViewDataDictionary的构造函数中,ViewData作为参数传入。

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