views:

329

answers:

1

Calling Html.RenderPartial("~/Views/Payments/MyControl.ascx"); from a view works if MyControl.ascx is a control that directly inherits System.Web.Mvc.ViewUserControl.

However, if the control inherits a new class that derives from System.Web.Mvc.ViewUserControl, the call to Html.RenderPartial("~/Views/Payments/MyDerivedControl.ascx"); fails, reporting that no such view exists.

Example derived System.Web.Mvc.ViewUserControl:

class MyDerivedControl : System.Web.Mvc.ViewUserControl
{
    public Method()
    {
        ViewData["SomeData"] = "test";
    }
}

Is there a workaround, or is there another way I should be doing this? Perhaps an HTML helper?

A: 

From MVC point of view it is not a good design to have your view provide data. Usually this is the responsibility of the controller. Depending on the context and what this data represents you could use an HTML helper or a write an action filter. Here's an example with a custom action filter:

public class SomeDataActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        filterContext.Controller.ViewData["SomeData"] = "test";
    }
}

And then decorate your action with this filter:

[SomeDataActionFilter]
public ActionResult Index()
{
    return View();
}
Darin Dimitrov
The view isn't providing data; my question is about the view passing provided data to a **derived** partial view and the resulting error when attempting to display it after interpretation (by the derived ViewUserControl class). Where the data came from is not of consequence.
FreshCode
@FreshCode, I have no idea why this particular exception occurs. All I can tell you is that views are not supposed to be inherited the way you are trying to in an MVC application. Views are just for displaying data coming from the controller. There are techniques such as Master Pages, Partial Views, HTML Helpers that allow you to compose and reuse functionality in Views. In the default ASP.NET MVC project template generated by VS there's not even a `.cs` file associated to your `ascx` controls.
Darin Dimitrov