我有以下类(class):
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)
现在我想做的是创建一个扩展方法,其中包含上述内容并且我可以在每个 View 中调用它。我尝试过执行以下操作。我认为我走在正确的轨道上,但我不知道如何做相当于“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 ) );
}
}
最佳答案
您可以编写一个采用 λ 表达式的强类型助手:
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)
<小时/>
更新:
根据评论部分的要求,这是该帮助程序的修订版本:
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
类型的编辑器模板。
关于asp.net-mvc - 如何在扩展方法中使用 HTML 帮助器方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8187322/