2011-11-18 80 views
4

我有以下类别:如何在扩展方法中使用HTML助手方法?

public class Note 
{ 
    public string Text { get; set; } 
    public RowInfo RowInfo { get; set; } 
} 

public class RowInfo 
{ 
    [DisplayName("Created")] 
    public DateTime Created { get; set; } 
    [DisplayName("Modified")] 
    public DateTime Modified { get; set; } 
} 

在我看来,我有一个用正确的名称和值创建HTML如下:

Html.HiddenFor(model => model.Note.Created) 

现在我所要做的是创建一个扩展方法将包含上述内容,并且可以在每个视图中调用。我尝试了以下操作。我认为我在正确的轨道上,但我不知道如何做相当于“model => model.Note.Created”有人可以给我一些建议,我该如何做到这一点,以及我需要用圆括号替换文本。我没有模型,但我可以通过其他方式做到这一点,所以隐藏的字段将查看我的类以获取正确的DisplayName,就像它在上面那样?

namespace ST.WebUx.Helpers.Html 
    { 
    using System.Web.Mvc; 
    using System.Web.Mvc.Html 
    using System.Linq; 

public static class StatusExtensions 
{ 
    public static MvcHtmlString StatusBox(this HtmlHelper helper, RowInfo RowInfo) 
    { 
     return new MvcHtmlString( 
      "Some things here ... " + 
      System.Web.Mvc.Html.InputExtensions.Hidden(for created field) + 
      System.Web.Mvc.Html.InputExtensions.Hidden(for modified field)); 
    } 

} 

回答

4

你可以写一个强类型的辅助拍摄λ表达式:

public static class StatusExtensions 
{ 
    public static IHtmlString StatusBox<TModel, TProperty>(
     this HtmlHelper<TModel> helper, 
     Expression<Func<TModel, TProperty>> ex 
    ) 
    { 
     return new HtmlString(
      "Some things here ... " + 
      helper.HiddenFor(ex)); 
    } 
} 

然后:

@Html.StatusBox(model => model.RowInfo.Created) 

UPDATE:

的要求,在评论部分这里是一个修订版本助手:

public static class StatusExtensions 
{ 
    public static IHtmlString StatusBox<TModel>(
     this HtmlHelper<TModel> helper, 
     Expression<Func<TModel, RowInfo>> ex 
    ) 
    { 
     var createdEx = 
      Expression.Lambda<Func<TModel, DateTime>>(
       Expression.Property(ex.Body, "Created"), 
       ex.Parameters 
      ); 
     var modifiedEx = 
      Expression.Lambda<Func<TModel, DateTime>>(
       Expression.Property(ex.Body, "Modified"), 
       ex.Parameters 
      ); 

     return new HtmlString(
      "Some things here ..." + 
      helper.HiddenFor(createdEx) + 
      helper.HiddenFor(modifiedEx) 
     ); 
    } 
} 

然后:

@Html.StatusBox(model => model.RowInfo) 

不用说,自定义HTML佣工应该被用来生成HTML的一小部分。复杂性可能会迅速增长,在这种情况下,我会建议您使用RowInfo类型的编辑器模板。

+0

如果我想将RowInfo传递给我的StatusBox扩展,然后有一个帮助程序,例如打印helper.HiddenFor对于RowInfo.Created和RowInfo.Modified字段?我能以同样的方式做到吗? –

+0

@梅丽莎,我用一个例子更新了我的答案。 –

+0

太好了。你让我的生活变得更简单了。非常感谢 !! –