通常我通过@ Html.RenderModel渲染我的表单,但这次我有一个复杂的渲染逻辑,我手动渲染它.我决定为一个属性创建一个编辑器模板.这是代码(从默认对象编辑器模板实现粘贴的副本):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<% var modelMetadata = ViewData.ModelMetadata; %>
<% if (modelMetadata.HideSurroundingHtml) { %>
<%= Html.Editor(modelMetadata.PropertyName) %>
<% } else { %>
<% if (!String.IsNullOrEmpty(Html.Label(modelMetadata.PropertyName).ToHtmlString())) { %>
<div class="editor-label"><%= Html.Label(modelMetadata.PropertyName) %></div>
<% } %>
<div class="editor-field">
<%= Html.Editor(modelMetadata.PropertyName) %>
<%= Html.ValidationMessage(modelMetadata.PropertyName) %>
</div>
<% } %>
Run Code Online (Sandbox Code Playgroud)
以下是我如何使用它:
@Html.EditorFor(x => x.SomeProperty, "Property") //"Property" is template above
Run Code Online (Sandbox Code Playgroud)
但它不起作用:无论DisplayName如何都会呈现标签,并且根本不呈现编辑器(在Watches Html.Editor中(modelMetadata.PropertyName显示空字符串).我做错了什么?
以下列模型为例:
namespace MyNamespace.Model
{
//you can only have two friends for the sake of simplicity in this example :P
public class Friends{
public Person NormalFriend { get; set; }
public Hipster HipsterFriend { get; set; }
}
public class Person{
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
public class Hipster : Person
{
public HatType HatPreference { get; set; }
public int CoolPoints { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
假设我们正在尝试添加我们的两个朋友,一个普通朋友和一个时髦朋友:
Create.cshtml: …
我一直在尝试为 ASP.NET Core 2 中的抽象类实现模型绑定程序,但没有成功。
我特别研究了两篇看起来非常好的文章:
http://www.dotnetcurry.com/aspnet-mvc/1368/aspnet-core-mvc-custom-model-binding
我有两个目标正在努力实现
这是我基于上述文章的代码。
public class Trigger
{
public ActionBase Action { get; set; }
}
[ModelBinder(BinderType = typeof(ActionModelBinder))]
public abstract class ActionBase
{
public string Type => GetType().FullName;
public ActionBase Action { get; set; }
}
public class ActionA : ActionBase
{
public int IntProperty { get; set; }
}
public class ActionB : ActionBase
{
public string StringProperty { get; set; }
}
public class ActionModelBinderProvider : …Run Code Online (Sandbox Code Playgroud)