Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - MVC3 - Passing data beyond the model to Partial view

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<CustomTable>)ViewBag.Table);

Is what I have now. Can I add something else without changing my Model?

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

I see ViewDataDictionary as a param. I am not sure what this object does or if this meets my need.

question from:https://stackoverflow.com/questions/7177153/mvc3-passing-data-beyond-the-model-to-partial-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<CustomTable>)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<List<CustomTable>, string>((List<CustomTable>)ViewBag.Table, "Extra data"));

The model type for the partial would then be:

@model Tuple<List<CustomTable>, string>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...