2012-06-21 23 views
1

目前,我正在編寫2個幫助器方法來擴展一個實現,我使用「IHtmlString」,如何通過使用「MvcHtmlString」將其轉換爲一種方法?幫助...如何將「IHtmlString」更改爲「MvcHtmlString」?

public static IHtmlString ExceptionValidationSummary(this HtmlHelper helper) 
    { 
     const string template = "<div class=\"ui-widget\"><div class=\"ui-state-error ui-corner-all\" style=\"padding:0 .7em\"><div>" + 
           "<span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: .3em;\"></span>" + 
           "<strong>Validation Exceptions:</strong></div><div style=\"margin-top: 5px;\"> " + 
           "<ul style=\"font-weight: normal;\">{0}</ul></div></div></div>"; 

     StringBuilder exceptionList = new StringBuilder(); 

     // Iterate through the exceptions 
     foreach (var error in helper.ViewData.ModelState.SelectMany(modelState => modelState.Value.Errors)) 
     { 
      exceptionList.Append(string.Format("<li>{0}</li>", error.ErrorMessage)); 
     } 

     return exceptionList.Length.Equals(0) ? string.Format("").Raw() : string.Format(template, exceptionList).Raw(); 

    } 

    public static IHtmlString Raw(this string value) 
    { 
     return new HtmlString(value); 
    } 
+1

我不明白的問題 - 你想,而不是返回抽象IHtmlString接口的具體MvcHtmlString實例?爲什麼不直接返回一個MvcHtmlString實例? – Dai

+0

如何連接「模板」和「exceptionList」以在我上面的情況下返回一個MvcHtmlString? – user584018

回答

1

雖然我期望的StringBuilder.ToString()方法通過string.Format()被隱式調用,如果沒有發生,顯式調用ToString()方法是這樣的:

string.Format(template, exceptionList.ToString()) 

而且,則聲明您的方法返回IHtmlString。如果您更改簽名以使用MvcHtmlString,則會告訴編譯器您所需的返回類型。在這一點上,它只是一個確保返回值問題的更新聲明匹配:

return MvcHtmlString.Create(string.Format(template, exceptionList.ToString()));