2012-08-26 30 views
5

我有點迷路了創建一個MVC3幫手。我有我的幫手,只是創建一個表達式作爲參數傳遞的行。MVC3如何使用@<text></text>作爲html幫手參數

我想用我的HtmlHelper這樣的:

@Html.AddTableFormField(model => model.UserName, @<text> 
     @Html.EditorFor(m => m.UserName)<span class="warning">Use only letters</span> 
    </text>) 

這是我的HtmlHelper(一些無關痛癢的代碼移除):

public static MvcHtmlString AddTableFormField<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> property, Expression<Func<TModel>> customFormat = null) 
    { 
     var metadata = ModelMetadata.FromLambdaExpression(property, htmlHelper.ViewData); 

     string displayName = metadata.DisplayName; 

     var propName = metadata.PropertyName; 

     if (string.IsNullOrWhiteSpace(displayName)) 
      displayName = propName; 

     MvcHtmlString htmlCustomFormat = null; 

     if (customFormat != null) 
     { 
      var deleg = customFormat.Compile(); 
      htmlCustomFormat = new MvcHtmlString(deleg().ToString()); 
     } 
     else 
      htmlCustomFormat = htmlHelper.EditorFor(property); 

     return new MvcHtmlString(string.Format("<tr>"+ 
       "<td class=\"form-label\">"+ 
        "<label class=\"editor-label\" for=\"{0}\">{1}<label>"+ 
       "</td>"+ 
       "<td class=\"form-data\">"+ 
        "{2}"+ 
       "</td>"+ 
      "</tr>", 
      propName, displayName, htmlCustomFormat)); 
    } 

我甚至無法編譯,因爲@<text>...</text>參數對HtmlHelper無效,因爲它是'lambda表達式',不能轉換爲表達式>

任何人都可以幫助解決它?我只是想將任何種類的@<text></text>傳遞給我的HtmlHelper,並且它只是編譯它並將它的MvcHtmlString放入格式化的返回中。

SOLUTION:

我發現我一直在尋找這個帖子: ASP.Net MVC3 - Pass razor markup as a parameter

參數類型爲@<text></text>必須是Func<object, HtmlHelper>

回答

2

<text>...</text> or @:是剃刀語法(不是C#),以避免html元素,所以我usggestion將是你使用字符串作爲參數,而不是@<text>

+1

但是這樣做會使參數中使用html helpers失去強類型的優勢。 無論如何,如果我使用字符串,是否有一種方法可以在我的Helper中進行編譯? (想象一下,由我的標記示例的內容組成的字符串) – IPValverde

相關問題