Question

I'm using Asp.net MVC 1 and I would really like my controller actions to use StronglyTyped View(data) calls that enforce type checking at compile time and still let me use aspx pages under the default view engine. The ViewPages I call are strongly typed, but errors in the action's call to View(data) can't be caught at compile time because the built in Controller View(data) method isn't strongly typed and doesn't even check to see if the page exists at compile time.

I've implemented a partial solution (code below) using this post but (1) I can't get the generic View function to recognize the Type of strong view pages unless I create a code behind for the strongly typed view, and (2) Intellisense and refactoring don't work properly with this method which makes me doubt the reliability of the method I'm using.

Question: Is there a better way to get type enforcement when calling Views from actions?

Alternative: Is there an alternative method where my action method can create an instance of a viewpage, set some properties directly and then render out its HTML to the action response?

Code: Here's the base Class all my Controllers Inherit from to achieve what I have so far:

 public class StrongController : Controller 
    {

        protected ActionResult View<TView, TModel>(TModel model)
            where TView : ViewPage<TModel>
            where TModel : class
        {
            return View(typeof(TView).Name, model);
        }


    }

And here's an example Controller in use: namespace ExampleMVCApp.Controllers {

    public class HomeController : StrongController 
    {

        public ActionResult Index()
        {
            return View<ExampleMVCApp.Views.Home.Index, ExampleData>(new ExampleData());
        }


    }
}

ViewPage Code Behind Required for Type Recognition... Aspx header didn't work

namespace ExampleMVCApp.Views.Home
{
    public class Issue : System.Web.Mvc.ViewPage<ExampleData>
    {
    }

}
Was it helpful?

Solution

I think you should give the T4MVC helpers a spin (one of the original announcements here). This would at least enable you to get rid of the code you already have, since these templates generate the code based on the Views you already have and you employ these "fake" method calls to address your views.

For having your calls to View to be strongly typed for the specific model declared by your view, I am not exactly sure if these helpers help you with that (though I suspect they do). However, if they don't you can still hack the T4MVC code to do so yourself or get in touch with the original author, David Ebbo, to suggest the feature for addition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top