2016-09-21 113 views
0

是否有可能重寫ASP.NET MVC的EditorForDisplayFor覆蓋ASP.NET MVC EditorFor

我想應用一些邏輯來判斷是否實際顯示內容或者只是輸出「」。

所以我想這樣做(僞):

public static MyEditorFor(this html) 
{ 
    if(ICanRender) 
    { 
    call HtmlEditorFor(original); 
    } 
    else 
    { 
    return EmtpyString; 
    } 
} 

這可能嗎?

+1

可能重複[在MVC中可以重寫一個編輯器模板](http://stackoverflow.com/questions/11599204/in-mvc-is-it-possible-to-override-an-editor-template ) –

+0

不知道_override_是什麼意思,但是你可以創建你自己的顯示和編輯器模板,這些模板將被這些方法用來呈現任何你想要的東西 –

+0

我不同意,它不顯示任何我在這個問題中需要的解決方案。我不想提供不同的模板。我想把這個問題的邏輯建議添加一個不同的命名模板 – dagda1

回答

2

這聽起來像你想的延伸:

public static MvcHtmlString MyEditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) { 
    if(ICanRender) 
    { 
     return System.Web.Mvc.Html.EditorExtensions.EditorFor(html, expression); 
    } 
    else 
    { 
     return MvcHtmlString.Create(string.Empty); 
    } 
} 

這codesnipped是未經測試,但它應該工作。

1

您可以創建自己的Html助手作爲HtmlHelperHtmlHelper<TModel>的擴展方法。只需添加如下擴展方法:

public static MvcHtmlString MyEditorFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expression) 
{ 

} 

當然,您可以根據需要添加其他參數。在此方法內訪問htmlHelper的所有方法。返回普通EditorFor例如:

public static MvcHtmlString MyEditorFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expression) 
{ 
    return htmlHelper.EditorFor(expression); 
} 

或者根據需要,你可以創建自己的元素(或它們的組合):

public static MvcHtmlString MyEditorFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expression) 
{ 
    TagBuilder div = new TagBuilder("div"); 
    div.AddCssClass("some-css"); 

    MvcHtmlString editor = htmlHelper.TextBoxFor(expression); 
    div.InnerHtml = editor.ToHtmlString(); 

    return new MvcHtmlString(div.ToString()); 
} 

瞭解更多關於TagBuilderhere

0

您可以將custon模型置於「views/shared/EditorTemplates」或「views/shared/DisplayTemplates」下,並將這些文件放入[Model name] .cshtml中。

例:DateTime.cshtml

這樣,所有的編輯器,並顯示在您的模型的屬性將遵循DateTime.cshtml邏輯定義DateTime類型。

問題是如果你想檢索你想要的字段,你將不得不處理ViewData.TemplateInfo中的HTML。