MVC3 - Passing data beyond the model to Partial view

后端 未结 4 385
天命终不由人
天命终不由人 2021-01-30 13:18

Is there a way to pass a piece of extra data along with a model to a Partial view?

E.G.

@Html.Partial(\"_SomeTable\", (List)ViewBag.Tabl

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 13:59

    ViewDataDictionary can be used to replace the ViewData dictionary in the partial view... If you don't pass a ViewDataDictionary parameter then the parial's viewdata is the same as the parents.

    An example of how to use it in the parent is:

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

    Then within the partial you can access this obj as follows:

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

    A completely different approach woud be to use the Tuple class to group both the original model and extra data together as follows:

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

    The model type for the partial would then be:

    @model Tuple, string>
    

    Model.Item1 gives the List object and Model.Item2 gives the string

提交回复
热议问题