Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing parameters to my partial view?

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?

like image 366
mrblah Avatar asked Dec 15 '09 17:12

mrblah


People also ask

Can partial view have controller?

It does not require to have a controller action method to call it. Partial view data is dependent of parent model. Caching is not possible as it is tightly bound with parent view (controller action method) and parent's model.

Can we use script in partial view?

A Note About Script Binding for Partial ViewsJavaScript functions can be bound to elements on the partial view; the partial view is rendered at the same time as the parent view. This happens when loading the partial view with a @Html. Action helper method, as in this section from Edit.


2 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> <% } %> 
like image 189
Darin Dimitrov Avatar answered Oct 01 '22 11:10

Darin Dimitrov


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 %> 
like image 31
John Farrell Avatar answered Oct 01 '22 10:10

John Farrell