我有以下课程:
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 ) );
}
}
解决方法
您可以编写一个带有λ表达式的强类型助手:
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,RowInfo>> ex
)
{
var createdEx =
Expression.Lambda<Func<TModel,DateTime>>(
Expression.Property(ex.Body,"Created"),ex.Parameters
);
var modifiedEx =
Expression.Lambda<Func<TModel,"Modified"),ex.Parameters
);
return new HtmlString(
"Some things here ..." +
helper.HiddenFor(createdEx) +
helper.HiddenFor(modifiedEx)
);
}
}
接着:
@Html.StatusBox(model => model.RowInfo)
不用说,应该使用自定义HTML帮助程序来生成HTML的一小部分.复杂性可能会快速增长,在这种情况下,我建议您使用RowInfo类型的编辑器模板.
