Inheriting from ViewPage forces explicit casting of model in view
- by Martin Hansen
I try to inhering from ViewPage as shown in this question http://stackoverflow.com/questions/370500/inheriting-from-viewpage
But I get a
Compiler Error Message: CS1061: 'object' does not contain a definition for 'Spot' and no extension method 'Spot' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
My viewpage, normally I can do Model.ChildProperty(Spot) when I inherit from ViewPage directly, so I do that here too. But it fails.
<%@ Page Language="C#" Inherits="Company.Site.ViewPageBase<WebSite.Models.SpotEntity>" %>
<h1><%= Html.Encode(Model.Spot.Title) %></h1>
To get it working correctly I have to do like this:
<%@ Page Language="C#" Inherits="Company.Site.ViewPageBase<WebSite.Models.SpotEntity>" %>
<h1><%= Html.Encode(((WebSite.Models.SpotEntity)Model).Spot.Title) %></h1>
Here is my classes:
namespace Company.Site
{
public class ViewPageBase<TModel> : Company.Site.ViewPageBase where TModel:class
{
private ViewDataDictionary<TModel> _viewData;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public new ViewDataDictionary<TModel> ViewData
{
get
{
if (_viewData == null)
{
SetViewData(new ViewDataDictionary<TModel>());
}
return _viewData;
}
set
{
SetViewData(value);
}
}
protected override void SetViewData(ViewDataDictionary viewData)
{
_viewData = new ViewDataDictionary<TModel>(viewData);
base.SetViewData(_viewData);
}
}
public class ViewPageBase : System.Web.Mvc.ViewPage
{
}
}
So how do I get it to work without the explicit cast?