Rendering partial views with a model and htmlhelper
ASP .NET MVC 1
I'd like to show a partial view base on a model, and I'd like that to have a fairly short command for that. So I saw a way of using both a HtmlHelper and a controller (And I'd use another controller for that, not the controller currently used).
But somehow it still gives an error, though I think the method starts to look as it should.
So what am I doing wrong? (If I call the method directly in the ASPX-page, it succeeds. But it should be possible to use a HtmlHelper for that).
public static void RenderPartialView(this HtmlHelper html, string action, string controller, object model)
{
var context = html.ViewContext;
RouteData rd = new RouteData(context.RouteData.Route, context.RouteData.RouteHandler);
rd.Values.Add("controller", controller);
rd.Values.Add("action", action);
rd.Values.Add("model", model);
IHttpHandler handler = new MvcHandler(new RequestContext(context.HttpContext, rd));
handler.ProcessRequest(System.Web.HttpContext.Current);
}
Part in the ASCX-page:
<% Html.RenderPartialView("Show", "Intro", Model.Intro); %>
Error given: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'RenderPartialView' and no extension method 'RenderPartialView' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be fou开发者_JAVA百科nd (are you missing a using directive or an assembly reference?)
Why don't you use Html.RenderPartial ? It's the correct way to render a partial view. No need to make another request.
<% Html.RenderPartial("Show", Model.Intro); %>
Your call does not succeed beacause when you use an extension method in a "non static" way (i.e, as if the method belongs to an instance), you must omit the first parameter. The correct call would be
<% Html.RenderPartialView("Show", "Intro", Model.Intro); %>
Hope it helps
Cédric
Add
<add namespace="Namespace-Of-RenderPartialView-Class"/>
to your web.config file.
With extension methods, you don't need to include the first argument (the "this HtmlHelper html"). That is handled by the compiler when using extension methods. It is inferred based on the object you're calling the method on.
精彩评论