views:

338

answers:

3

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 found (are you missing a using directive or an assembly reference?)

A: 

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.

Patrick Steele
You're right, but it does no harm. Same problem when I leave that argument out. I adjusted the text.
Johan
+3  A: 

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

Cédric Rup
Hmm, I want to have a partial view of another controller. RenderPartial only works for the current controller, right?
Johan
Damn, I should put it in the shared folder. That works, thanks.
Johan
relative View names can be used ;o)
Cédric Rup
You're right, Shared folder is even more relevant in this case...
Cédric Rup
+1  A: 

Add

<add namespace="Namespace-Of-RenderPartialView-Class"/>

to your web.config file.

griZZZly8