我有一个名为 LocalizedString
的类,它是在我的 asp.net mvc 3 项目中引用的外部库中定义的。
我在 ~\View\Shared\EditorTemplates
文件夹中创建了一个名为 LocalizedString.cshtml
的编辑器模板。
我有以下模型
public class Region
{
public LocalizedString Title { get; set; }
}
我有以下测试页面:
@model Region
@Html.EditorForModel()
@Html.EditorFor(x => x.Title)
当我调用 EditorForModel
时,不会调用 LocalizedString
的编辑器模板,但当我显式调用 EditorFor(x => x.Title) 时,它会呈现
所以我知道我没有推荐问题。
为什么当我调用 EditorForModel
(或其等效的 EditorFor(x => x)
)时我的编辑器模板被忽略
更新
我创建了一个新项目来重现此行为。我刚刚使用了默认的 ASP.NET MVC 3 Internet 应用程序。
Index.cshtml
@model MvcApplication1.Models.Region
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
@Html.EditorForModel()
HomeController.cs
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(new Region());
}
}
}
Region.cs
namespace MvcApplication1.Models
{
public class Region
{
public Region()
{
this.Name = "RegionInstance";
this.Title = new LocalizedString();
}
public string Name { get; set; }
public LocalizedString Title { get; set; }
}
}
LocalizedString.cs
namespace MvcApplication1.Models
{
public class LocalizedString
{
public LocalizedString()
{
this.Name = "LocalizedStringInstance";
}
public string Name { get; set; }
}
}
如果运行此程序,输出将仅显示区域名称的文本输入。 LocalizedString.cshtml 内容永远不会输出。
我还尝试在 Region.Title
属性上使用 UIHint
,但它仍然不显示。
最佳答案
结果发现这和Html.EditorForModel doesnt render complex types是同样的问题
默认情况下,ASP.NET MVC 不会呈现子复杂类型,正如我通过反射发现的那样
private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
{
if (metadata.ShowForEdit && metadata.ModelType != typeof (EntityState) && !metadata.IsComplexType)
return !templateInfo.Visited(metadata);
else
return false;
}
由System.Web.Mvc.Html.DefaultEditorTemplates
中的ObjectTemplate
调用。
检查IsComplexType
的行为后,我发现如果类型无法通过TypeConverter
转换为字符串,则该类型是复杂的。如果我为我的子模型创建一个 TypeConverter,它就会渲染。尽管这个解决方案并不理想,我可能会坚持使用 EditorFor
而不是 EditorForModel
。
using System;
using System.ComponentModel;
public class LocalizedStringTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
}
关于c# - 为什么当我调用 EditorForModel 时我的编辑器模板被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6782769/