I don't know if this is by design or not. But if it's by design, it's so inconsistent.
The EditorForModel
works for the root PageModel
, like this:
public class MyPageModel : PageModel, IUsersSelection {
public IEnumerable<int> UserIds {get;set;}
public MyEditModel EditModel {get;set;}
//...
}
public interface IUsersSelection {
IEnumerable<int> UserIds {get;set;}
}
I have an EditorTemplate
for IUsersSelection
(named UsersSelection.cshtml
) like this:
@model IUsersSelection
@Html.EditorFor(e => e.UserIds)
And in the MyPage.cshtml
, I use EditorForModel
like this:
@model MyPageModel
<!-- use explicit template name because the model Type does not exactly match -->
<!-- this works fine -->
@Html.EditorForModel("UsersSelection")
The EditorForModel
above works just fine.
But now I have another EditorTemplate
targeting another model, name it MyEditModel
:
public class MyEditModel : IUsersSelection {
public IEnumerable<int> UserIds {get;set;}
}
Its EditorTemplate
looks like this:
@model MyEditModel
@Html.EditorForModel("UsersSelection")
Now in my MyPage.cshtml
, I also have this:
@model MyPageModel
<!-- this renders nothing -->
@Html.EditorFor(e => e.EditModel)
The EditorForModel
in the editor template for MyEditModel
does not work.
Do you have any idea on what could be wrong? Or it's just by design (the EditForModel
works only for interface if it's used for the root PageModel, but not for editor template's model).
UPDATE:
Looks like the EditorForModel
does not work inside editor template at all (no matter the model is interface or not). This may be by design, but look at how I use the interface, this limitation is a bit inconvenient. Now I have to expose a property on the main model for the interface model, like this:
public class UsersSelection : IUsersSelection {
}
public class MyEditModel {
//this does not look neat as the original (desired) model
public UsersSelection UsersSelection {get; set;}
}
//in the editor template for `MyEditModel`
@Html.EditorFor(e => e.UsersSelection, "UsersSelection")
I've found out that the EditorForModel
does not work for the same model instance with the current editor template's model. The following model works:
public class MyEditModel : IUsersSelection {
public IUsersSelection UsersSelection {get; set;}
}
But the following won't (because UsersSelection
set to the same model instance of MyEditModel
):
public class MyEditModel : IUsersSelection {
public MyEditModel(){
UsersSelection = this;
}
public IUsersSelection UsersSelection {get; set;}
}