【问题标题】:Call asp.net mvc Html Helper within custom html helper with expression parameter使用表达式参数在自定义 html 助手中调用 asp.net mvc Html Helper
【发布时间】:2010-05-11 11:59:39
【问题描述】:

我正在尝试在 asp.net mvc 框架中编写一个 html 助手扩展。

public static MvcHtmlString PlatformNumericTextBoxFor<TModel>(this HtmlHelper instance, TModel model, Expression<Func<TModel,double>> selector)
        where TModel : TableServiceEntity
    {
        var viewModel = new PlatformNumericTextBox();

        var func = selector.Compile(); 

        MemberExpression memExpession = (MemberExpression)selector.Body;
        string name = memExpession.Member.Name;

        var message = instance.ValidationMessageFor<TModel, double>(selector);

        viewModel.name = name;
        viewModel.value = func(model);
        viewModel.validationMessage = String.Empty;

        var result = instance.Partial(typeof(PlatformNumericTextBox).Name, viewModel);

        return result;

    }

线

var message = instance.ValidationMessageFor<TModel, double>(selector);

有语法错误。但我不明白。错误是: Fehler 2 "System.Web.Mvc.HtmlHelper" enthält keine Definition für "ValidationMessageFor", und die Überladung der optimizationen Erweiterungsmethode "System.Web.Mvc.Html.ValidationExtensions.ValidationMessageFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>)" weist einige ungültige Argumente auf. C:\Projects\WorkstreamPlatform\WorkstreamPlatform_WebRole\Extensions\PlatformHtmlHelpersExtensions.cs 97 27 WorkstreamPlatform_WebRole

所以根据消息,参数无效。但该方法实际上是这样声明的:

    public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression);

所以实际上它应该可以工作。

【问题讨论】:

  • 如果您可以翻译异常消息会有所帮助:)

标签: asp.net-mvc lambda expression-trees html-helper


【解决方案1】:

将您的方法声明更改为:

public static MvcHtmlString PlatformNumericTextBoxFor<TModel>(
    this HtmlHelper<TModel> instance, 
    TModel model, 
    Expression<Func<TModel,double>> selector) where TModel : TableServiceEntity
{

}

注意通用的this HtmlHelper&lt;TModel&gt;。第二个参数也不是必需的,因为您可以从强类型帮助器中检索模型:

var model = instance.ViewData.Model;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多