我有一个这样的模型:
public class ParentViewModel
{
public class ChildViewModel { get; set; }
// other properties
}
然后在ParentViewModel
的视图中,我这样做:
@Html.EditorFor(model => model.ChildViewModel)
即使Model.ChildViewModel
为null
,它也会执行我的自定义编辑器模板。为什么?我认为MVC非常聪明,只有在有值时才渲染视图/模板。 (例如null
的默认模板是不渲染任何东西)。
因为目前,我必须将HTML包装在我的自定义编辑器模板中:
@if (Model != null)
这看起来很傻。
这是一个已知问题吗?
我使用的是ASP.NET MVC 3,Razor。
答案 0 :(得分:2)
您可以使用新的扩展方法,而不是在部分或内部之前测试null。这也为您提供了更多如何处理null模型的选项。这是我使用的扩展,它将测试null并返回空字符串或null结果的不同部分。这对于页面超出范围的寻呼机等内容尤其有用,因为您可以单独使用“无结果”信息。
namespace System.Web.Mvc.Html
{
public static class nullpartials
{
public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, object Model)
{
if (Model == null)
return MvcHtmlString.Empty;
else
return helper.Partial(Partial, Model);
}
public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)
{
if (Model == null)
return helper.Partial(NullPartial);
else
return helper.Partial(Partial, Model);
}
public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, object Model, ViewDataDictionary viewdata)
{
if (Model == null)
return MvcHtmlString.Empty;
else
return helper.Partial(Partial, Model, viewdata);
}
public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)
{
if (Model == null)
return helper.Partial(NullPartial, viewdata);
else
return helper.Partial(Partial, Model, viewdata);
}
public static void RenderNullPartial(this HtmlHelper helper, string Partial, object Model)
{
if (Model == null)
{
return;
}
else
{
helper.RenderPartial(Partial, Model);
return;
}
}
public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)
{
if (Model == null)
{
helper.RenderPartial(NullPartial);
return;
}
else
{
helper.RenderPartial(Partial, Model);
return;
}
}
public static void RenderNullPartial(this HtmlHelper helper, string Partial, object Model, ViewDataDictionary viewdata)
{
if (Model == null)
{
return;
}
else
{
helper.RenderPartial(Partial, Model, viewdata);
return;
}
}
public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)
{
if (Model == null)
{
helper.RenderPartial(NullPartial, viewdata);
return;
}
else
{
helper.RenderPartial(Partial, Model, viewdata);
return;
}
}
}
}
修改
对不起,我错过了关于EditorTemplates的问题。但是我认为没有理由相同的方法不能用于EditorFor,你只需要复制一些方法签名。
答案 1 :(得分:1)
我不认为MVC那么聪明。它期望如果你调用一个render方法(displayFor,EditFor,Partial)并向它发送一个模型,那么该模型将有一个值(否则为NullReferenceException)。据我所知,您的选择是: