开发者

how to pass parameters to partial view to show db content?

开发者 https://www.devze.com 2022-12-23 13:12 出处:网络
I am getting my content from a database. How can i use partial views to show content on page using that database?

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?


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.


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%>
0

精彩评论

暂无评论...
验证码 换一张
取 消