tags:

views:

44

answers:

2

I am getting my content from a database. How can i use partial views to show content on page using that database?
database table: Content
[Id, Content] these are 2 fields

i want to get the content from db using partial views.
How i will pass an id to a partial view and show the content in view page?

A: 

Inside your view, use the Html.RenderPartial function. There are a few different uses:

You can pass in a model to the partial view: <% Html.RenderPartial("partialName", model); %>

Or you can pass in a whole new ViewDataDictionary: <% Html.RenderPartial("partialName", viewData); %>

For the full documentation, see here.

EDIT: (Answer to comment):

I would include that data as part of you're view's model. For example, let's say in your model you have:

 List<Person> People;

In your view, you want to loop through each one of these, and use a PartialView to display the details:

 <% foreach( var p in Model.People){ %>
         <p> <% Html.RenderPartial("personPartial", p); %> </p>
 <%}%>

Now, your PartialView might look like:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Person>" %>
<%=Model.PersonName%>
mlsteeves
What will i pass as model?Lets say i want to show content for different paragraphs like this <p>[data here from db whose id=5]</p>, <p>[data here from db whose id=7]</p> and so on..
coure06
I dont want to show all p in Model.People, just want to show with some id like 5,8 etc.
coure06
Then only add that item to the Model. I was using the list as an example. The key is to add the object itself into the model, not just the ID of it.
mlsteeves
A: 

You could use Html.RenderAction:

public class MyController 
{
    [ChildActionOnly]
    public ActionResult Foo(int id) 
    {
        var content = GetContentFromDatabase(id);
        return Content(content, MediaTypeNames.Text.Html);
    }
}

And in your view include the partial:

<%= Html.RenderAction("foo", "mycontroller", new { id = 5 }) %>

Remark: RenderAction is part of the now released ASP.NET MVC 2 RTM. For ASP.NET MVC 1 you may take a look at the Futures assembly containing this extension method.

Darin Dimitrov