Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherited Interface property not found by Model Binding

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?

like image 259
Nate Kennedy Avatar asked Nov 01 '11 14:11

Nate Kennedy


1 Answers

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.

like image 132
wnascimento Avatar answered Nov 09 '22 18:11

wnascimento