有没有办法将一段额外的数据和模型传递给部分视图?
例如
@Html.Partial("_SomeTable", (List<CustomTable>)ViewBag.Table);
是我现在拥有的.我可以在不改变模型的情况下添加其他内容吗
@Html.Partial("_SomeTable", (List<CustomTable>)ViewBag.Table, "TemporaryTable");
我将ViewDataDictionary视为一个参数.我不确定这个对象是做什么的,或者这是否符合我的需要.
Mar*_*oth 66
ViewDataDictionary可用于替换局部视图中的ViewData字典...如果未传递ViewDataDictionary参数,则parial的viewdata与父项相同.
如何在父级中使用它的示例是:
@Html.Partial("_SomeTable", (List<CustomTable>)ViewBag.Table, new ViewDataDictionary {{ "Key", obj }});
Run Code Online (Sandbox Code Playgroud)
然后在部分内你可以访问这个obj如下:
@{ var obj = ViewData["key"]; }
Run Code Online (Sandbox Code Playgroud)
一种完全不同的方法是使用Tuple类将原始模型和额外数据组合在一起,如下所示:
@Html.Partial("_SomeTable", Tuple.Create<List<CustomTable>, string>((List<CustomTable>)ViewBag.Table, "Extra data"));
Run Code Online (Sandbox Code Playgroud)
部分的模型类型将是:
@model Tuple<List<CustomTable>, string>
Run Code Online (Sandbox Code Playgroud)
Model.Item1给出List对象,Model.Item2给出字符串
我也遇到过这个问题.我想要多次复制代码片段,并且不想复制粘贴.代码会略有不同.在查看其他答案之后,我不想走那条确切的路线,而是决定只使用平原Dictionary.
例如:
parent.cshtml
@{
var args = new Dictionary<string,string>();
args["redirectController"] = "Admin";
args["redirectAction"] = "User";
}
@Html.Partial("_childPartial",args)
Run Code Online (Sandbox Code Playgroud)
_childPartial.cshtml
@model Dictionary<string,string>
<div>@Model["redirectController"]</div>
<div>@Model["redirectAction"]</div>
Run Code Online (Sandbox Code Playgroud)