如何通过@<text></text>
传递扩展方法?
我创建了这个扩展类:
public class CustomPanel
{
public CustomPanel()
{
this.Fields = new List<string>();
}
private List<string> Fields { get; set; }
public void AddField(string format)
{
this.Fields.Add(format);
}
public MvcHtmlString GetHtml()
{
var sb = new StringBuilder();
foreach (var field in this.Fields)
sb.AppendFormat("{0} <br>", field);
return new MvcHtmlString(sb.ToString());
}
}
public static class PanelExtension
{
public static CustomPanel CreatePanel(this HtmlHelper html)
{
return new CustomPanel();
}
}
当我打电话给方法时:
@{
var panel = @Html.CreatePanel();
}
panel.AddField(@<text>
@Html.LabelFor(model => model.BarCode)
@Html.CheckBoxFor(model => model.BarCode)
</text>)
发生以下错误:
&#34;&LT;&#34;在代码块的开头无效。只有标识符, 关键字,评论&#34;(&#34;和&#34; {&#34;有效。
我该如何解决这个问题?
感谢。
答案 0 :(得分:0)
我用更好的主意解决了这个问题。
我将表达式传递给方法,在里面我创建了html代码。
public class CustomField
{
public CustomField(MvcHtmlString label, MvcHtmlString input)
{
this.Label = label;
this.Input = input;
}
public MvcHtmlString Label { get; private set; }
public MvcHtmlString Input { get; private set; }
public override string ToString()
{
return string.Format("{0}{1}", this.Label, this.Input);
}
}
public class CustomPanel<TModel>
{
public CustomPanel(HtmlHelper<TModel> html)
{
if (html == null) throw new ArgumentNullException("html");
this.Html = html;
this.Fields = new List<CustomField>();
}
private HtmlHelper<TModel> Html { get; set; }
private List<CustomField> Fields { get; set; }
public void AddField<TValue>(Expression<Func<TModel, TValue>> expression)
{
this.Fields.Add(new CustomField(this.Html.LabelFor<TModel, TValue>(expression), this.Html.TextBoxFor<TModel, TValue>(expression)));
}
public MvcHtmlString GetHtml()
{
var sb = new StringBuilder();
foreach (var field in this.Fields)
sb.AppendFormat("{0} <br>", field);
return new MvcHtmlString(sb.ToString());
}
}
public static class PanelExtension
{
public static CustomPanel<TModel> CreatePanel<TModel>(this HtmlHelper<TModel> html)
{
return new CustomPanel<TModel>(html);
}
}
查看:
@{
var panel = @Html.CreatePanel();
panel.AddField(model => model.Reference);
panel.AddField(model => model.Barcode);
}
@panel.GetHtml()