passing parameters to my partial view?

Viewed 55862

I am calling my partial view like this:

 <% Html.RenderPartial("~/controls/users.ascx"); %>

Can I pass parameters to partial view? How will I access them in the actual users.ascx page?

4 Answers

You could pass a model object to the partial (for example a list of strings):

<% Html.RenderPartial("~/controls/users.ascx", new string[] { "foo", "bar" }); %>

Then you strongly type the partial and the Model property will be of the appropriate type:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Collections.Generic.IEnumerable<string>>" %>

<% foreach (var item in Model) { %>
    <div><%= Html.Encode(item) %></div>
<% } %>

There is another overload for RenderPartial that will pass your model through.

<% Html.RenderPartial("~/controls/users.ascx", modelGoesHere); %>

How to access? Just like you normally would with any view:

<%= Model.MagicSauce %>
Related