【问题标题】:Is there a way to wrap Html.CheckboxFor, Html.TextboxFor, etc. methods with custom logic?有没有办法用自定义逻辑包装 Html.CheckboxFor、Html.TextboxFor 等方法?
【发布时间】:2011-06-09 15:32:45
【问题描述】:

我正在使用将数据和元数据包装在一个属性中的旧模型。对于这个问题,假设界面是:

pubic interface ILegacyCheckbox 
{
   bool Value { get; set; }
   bool Editable { get; set; }
}

我想用自己的方法包装 CheckBoxFor() 扩展方法,

public static MvcHtmlString LegacyCheckboxFor<TModel>(
    this HtmlHelper<TModel> html, 
    Expression<Func<TModel, ILegacyCheckbox>> expression)
{
    // wrap html.CheckBoxFor() method here by extracting the Value  
    // property and check if Editable is false, in which case add 
    // an htmlAttribute of "disabled=true"
}

有没有办法做这样的事情?我该从哪里开始?

任何帮助将不胜感激,

谢谢,
亚历克斯

【问题讨论】:

    标签: asp.net-mvc linq asp.net-mvc-3 expression-trees


    【解决方案1】:

    你可以试试这样的:

    public static MvcHtmlString LegacyCheckboxFor<TModel>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, ILegacyCheckbox>> expression)
    {
        var parameterName = ((MemberExpression)expression.Body).Member.Name;
        var compiled = expression.Compile().Invoke(html.ViewData.Model);
    
        if (editable)
            return html.CheckBox(parameterName, compiled.Value);
        else
            return html.CheckBox(parameterName, compiled.Value, new {disabled = "disabled"});
    }
    

    您可能还希望缓存已编译的表达式。

    我的示例使用 Html.CheckBox();我不确定如何使用 CheckBoxFor()。我也没有时间调查它,但至少这是一个开始的地方。

    【讨论】:

    • 是否需要用 html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName() 包装 parameterName 以确保它在 foreach 循环中有效?
    【解决方案2】:
    public static MvcHtmlString LegacyCheckboxFor<TModel>(
        this HtmlHelper<TModel> html,
        Expression<Func<TModel, ILegacyCheckbox>> expression)
    {
        MemberExpression memberExpression = expression.Body as MemberExpression;
        string parameterName = memberExpression.Member.Name;
    
        var checkbox = expression.Compile().Invoke(html.ViewData.Model);
    
        return new MvcHtmlString(
            string.Format(
            "<input type=\"checkbox\" name=\"{0}\" id=\"{0}\" value=\"{1}\" {2} />",
                parameterName,
                checkbox.Value,
                checkbox.Editable ? "disabled=true" : string.Empty));
    }
    

    【讨论】:

    • 我会使用 Html.CheckBox() 方法而不是构建字符串!
    • @Simon Bartlett 我如何在这个扩展中引用Html.CheckBox()
    • @Simon Bartlett 只有当参数是HtmlHelper 而不是HtmlHelper&lt;TModel&gt; 时才有效吗?没有 Intellisense 将 CheckBox 显示为方法
    • @David 它确实有效,我只是自己在 Visual Studio 中编写的。您需要导入 System.Web.Mvc.Html
    • @Simon Barlett Doh!--只有 System.Web.Mvc
    猜你喜欢
    • 1970-01-01
    • 2011-04-24
    • 2019-11-28
    • 1970-01-01
    • 2018-10-14
    • 2021-04-18
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多