ASP.NET how to render a custom template and pass it into a main template
I can make the same in Django
using render_to(...)
but ASP.NET.
I need to provide the different form in a single asp.net page, so I want to render custom form templates and pass it into a main page.
How to make this stuff?
I try t开发者_如何学Chis code
<%: Html.RenderPartial(ViewData["pd"].ToString(), ViewData)%>
and I get
'System.Web.Mvc.HtmlHelper<dynamic>' does not contain a definition for 'RenderPartial' and the best extension method overload 'System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(System.Web.Mvc.HtmlHelper, string)' has some invalid arguments
Sultan
I don't know Django, but from your description it looks like you are talking about partial views. So you could define a partial (~/Views/Home/Foo.ascx
):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>some contents</div>
and then in your main view include it:
<%= Html.Partial("Foo") %>
UPDATE:
Now that you have shown your code it seems that you are using the RenderPartial
method. This method doesn't return anything. It writes directly to the output. You are using it incorrectly. It should be used like this:
<% Html.RenderPartial(ViewData["pd"].ToString()); %>
or you could also use the Partial helper:
<%= Html.Partial(ViewData["pd"].ToString()) %>
Now as far as passing info to this partial is concerned I would very very very strongly recommend you getting rid of any ViewData and use strongly typed views and view models. So for example you would have a strongly typed main view to this model:
public class MyViewModel
{
public string Foo { get; set; }
public SomeOtherViewModel Bar { get; set; }
}
and then you will be able to do this:
<%= Html.Partial(Model.Foo, Model.Bar) %>
and then have your partial strongly typed to SomeOtherViewModel
:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeOtherViewModel>" %>
<div><%: Model.SomePropertyOfBar %></div>
Or even better, use the templated helpers Html.DisplayFor and Html.EditorFor. They are the best way to include partials into an ASP.NET MVC application.
If you are using WebForms, you can use MasterPage.
精彩评论