【问题标题】:Creating Generic View Components with Razor使用 Razor 创建通用视图组件
【发布时间】:2013-07-19 07:30:11
【问题描述】:

我想编写自己的自定义 HTML 帮助器来扩展现有的帮助器。例如。我想像这样创建扩展@Html.EditorFor

@Html.EditorFor(model => model.percent, new { data_a_sign="%", data_p_sign="s" })

变成:

@Html.PercentEditorFor(model => model.percent)

要怎么写呢?

这样的?

namespace AdminPortal.Helpers
{
    public static class HtmlHelpers
    {
        public static MvcHtmlString PercentEditorFor<TModel>(this HtmlHelper html, 
            Expression<Func<TModel>> expression)
        {
            // Some Magic?
        }
    }
}

任何指针将不胜感激。

【问题讨论】:

    标签: asp.net-mvc razor views html-helper


    【解决方案1】:

    只需从您自己的助手返回现有的 EditorFor 方法即可:

    public static MvcHtmlString PercentEditorFor<TModel>(this HtmlHelper html, 
                Expression<Func<TModel>> expression)
            {
                return html.EditorFor(...);
            }
    

    将自己修改的参数放入 EditorFor 方法。不需要魔法:)

    【讨论】:

    • 谢谢,但我想我误解了我的问题。我想将自定义类和数据属性添加到@Html.EditorFor 生成的输入中,但是当我添加这些属性时,它们会被模板忽略。
    • 我在这里提出了新问题:stackoverflow.com/questions/17742488/…
    猜你喜欢
    • 2011-12-15
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2011-10-09
    • 2023-03-11
    相关资源
    最近更新 更多