开发者

Call asp.net mvc Html Helper within custom html helper with expression parameter

开发者 https://www.devze.com 2022-12-29 17:56 出处:网络
I am trying to write an html helper extension within the asp.net mvc framework. public static MvcHtmlString PlatformNumericTextBoxFor<TModel>(this HtmlHelper instance, TModel model, Expression&

I am trying to write an html helper extension within the asp.net mvc framework.

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;

    }

The line

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

has a syntax error. But I do not understand it. The error is: Fehler 2 "System.Web.Mvc.HtmlHelper" enthält keine Definition für "ValidationMessageFor", und die Überladung der optimalen Erweiterungsm开发者_运维技巧ethode "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

So according to the message, the parameter is invalid. But the method is actually declared like this:

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

So actually it should work.


Change your method declaration to:

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

}

Notice the generic this HtmlHelper<TModel>. Also the second argument is not necessary as you can retrieve the model from the strongly typed helper:

var model = instance.ViewData.Model;
0

精彩评论

暂无评论...
验证码 换一张
取 消