部分的な前またはその内部で 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 で機能しない理由はわかりません。複製するメソッド シグネチャがいくつかあるだけです。