8

I'm getting stumped by this issue and I'm not sure if it's my lack of understanding of the MVC framework, the .NET framework, or what. But some explanation from any corner would be appreciated here.

What I'm trying to do: use ASP.NET MVC3 Model Binding to render HTML controls in a View. Specifically, I'm trying to bind to an interface rather than a concrete class.

The error: an ArgumentException "The property [blah] could not be found." is thrown during page load.

The code:

Interface IFoundation
{
  int Id { get; set; }
}

Interface IChild: IFoundation
{
  string Name { get; set; }
}

Class Concrete: IChild
{
  int Id { get; set; }
  string Name { get; set; }
}

The view:

@model IChild
@Html.EditorFor(x => x.Id)

When I try to load the view, an ArgumentException is thrown from the call to EditorFor() stating that the Id property cannot be found. However, if I instead bind to the Concrete class, binding works fine.

So does anyone know why EditorFor() would not be able to resolve the inherited property from the base interface?

Nate Kennedy
  • 383
  • 3
  • 15
  • 1
    That's what I've started doing: writing abstract classes that implement my interfaces. My concrete classes can then inherit and override the abstracts and (currently) I have my views binding to the abstracts as well. Not sure if binding to the abstract base classes is going to work for the views in the long run - Kaleb below suggests implementing ViewModel classes for the binding. I'm reluctant to start down that road at the moment, but I may end up there eventually. – Nate Kennedy Nov 01 '11 at 16:12
  • Kaleb's advice is great, Automapper/ViewModels is a good option. – wnascimento Nov 01 '11 at 20:08

1 Answers1

9

In base/abstract and concrete classes, properties, methods, etc are present. Interfaces, on the other hand, are implemented. Rules imposed by CLR.

See this article explaining about ModelBinding and relation on this difference (Class x Interface).

http://bradwilson.typepad.com/blog/2011/08/interface-attributes-class-attributes.html

I think it is your answer.

wnascimento
  • 1,949
  • 1
  • 19
  • 16
  • 1
    Thanks, that cleared it up for me. 'Course, it also raises a host of questions re: how i'm now going to manage my domain classes and what classes my views should be binding to, but those will be fodder for future SO questions! – Nate Kennedy Nov 01 '11 at 15:28
  • 1
    Take a look at [AutoMapper](http://automapper.org/) for what classes your views should be mapping to. The quick summary: create view-specific models (i.e. View Models) and map your domain classes to the view-specific models using something like `AutoMapper`. You could also create your own model binder. – Kaleb Pederson Nov 01 '11 at 15:37