asp.net-mvc – 如何在扩展方法中使用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 ) );
    }

}

解决方法

您可以编写一个带有λ表达式的强类型助手:
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类型的编辑器模板.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....