MVC EditorFor with compound model type?
-
26-10-2019 - |
Question
I would like to send a delegate or a command object as argument to an EditorFor along with the model object. I could use viewdata to send it with, but I would very much like it strongly typed. Is there any reasonable way to do this?
This is roughly what I'd like to be able to do in an editor template:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Pair<MyModelType, TheDelegate>>" %>
But how could I add my delegate to an expression such as this?
<%= Html.EditorFor(m => m.MyModelTypeField, "ThatEditor") %>
Solution
You can't do this in a strongly typed manner unless you modify your view model and have the controller pass the necessary information. So
public class MyModelTypeWithDelegate
{
public MyModelType MyModelType { get; set; }
public TheDelegate MyModelTypeDelegate { get; set; }
}
public class MyViewModel
{
public MyModelTypeWithDelegate MyModelTypeWithDelegate { get; set; }
}
and then:
<%= Html.EditorFor(m => m.MyModelTypeWithDelegate, "ThatEditor") %>
The other possibility is to pass it as additional viewdata but it won't be strongly typed:
<%= Html.EditorFor(m => m.MyModelTypeField, "ThatEditor", new { TheDelegate = someDelegate }) %>
and then inside your editor template:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyModelType>" %>
<%
var del = (TheDelegate)ViewData["TheDelegate"];
%>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow