您可以使用新的扩展方法,而不是在您的部分之前或内部测试 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,您只需复制更多的方法签名即可。