2011-08-24 95 views
36

有没有办法将一段额外的数据和模型一起传递到部分视图?MVC3 - 将数据传递到模型外部分视图

E.G.

@Html.Partial("_SomeTable", (List<CustomTable>)ViewBag.Table);

是什么,我现在有。我可以添加其他东西而不更改我的模型?

@Html.Partial("_SomeTable", (List<CustomTable>)ViewBag.Table, "TemporaryTable");

我看到ViewDataDictionary作为PARAM。我不确定这个对象是做什么的,或者这是否符合我的需要。

回答

64

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

如何在父使用它的一个例子是:

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

然后内的部分就可以访问此OBJ如下:

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

完全不同的方法woud是使用所述Tuple类组中的两个原始模型和额外数据一起如下:

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

然后局部模型类型是:

@model Tuple<List<CustomTable>, string> 

Model.Item1给List对象和Model.Item2给串

+2

我不能理解'新的ViewDataDictionary语法{{ “钥匙”,OBJ}} '。 新的ViewDataDictionary()中的圆括号()在哪里? – Mahmoodvcs

+2

当你有一个对象初始化程序时,它们是多余的。这就是代码直接在新的ViewDataDictionary之后。参见http://msdn.microsoft.com/en -us/library/bb531208.aspx –

+1

'@ {var obj = ViewBag.Key; }'也可以访问传递的数据 – MEC

2

你可以得到即便是聪明as shown here by Craig Stuntz

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

我也遇到了这个问题。我想要多次复制一段代码,并且不想复制粘贴。代码会略有不同。看过其他答案之后,我不想走这条确切的路线,而是决定只使用一个普通的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> 
相关问题