加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何在扩展方法中使用HTML帮助器方法?

发布时间:2020-12-15 23:57:14 所属栏目:asp.Net 来源:网络整理
导读:我有以下课程: 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
我有以下课程:
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类型的编辑器模板.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读