【问题标题】:"The type arguments cannot be inferred from the usage" in view with custom helper using standard helper鉴于使用标准帮助器的自定义帮助器,“无法从使用中推断出类型参数”
【发布时间】:2012-10-19 18:59:00
【问题描述】:

我有一些用于 MVC3 网站的表单,其中包含很多重复部分。所以我试图为此做一个帮手。按照互联网上的一个例子,我做了这个:

using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace Nop.Web.Themes.MyTheme.Extensions
{
    public static class FormLineHelper
    {
        public static MvcHtmlString FormLine<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
                                                                    Expression<Func<TModel, TProperty[]>> expression,
                                                                    object htmlAttributes = null)
        {
            TagBuilder tag = new TagBuilder("tr");
            tag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
            var member = (MemberExpression)expression.Body;
            string propertyName = member.Member.Name;

            tag.InnerHtml += String.Format("<td class='label'>{0}</label></td><td class='field'>{1}</td><td class='padding'>{2}</td>",
               htmlHelper.LabelFor(expression), htmlHelper.EditorFor(expression), htmlHelper.ValidationMessageFor(expression));

            return MvcHtmlString.Create(tag.ToString());
        }
    }
}

这编译得很好。但是当我这样做时

@model Nop.Plugin.MyPlugin.Models.ViewModel

@{
    Layout = "../Shared/_Root.cshtml";
}

<div class="form">
<div class="form-top"></div>
<div class="form-center">

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table>
    @Html.FormLine(model => model.FirstName)
   </table>
}
</div>
<div class="form-bottom"></div>
</div>

我确保 web.config 包含

<compilation debug="true" targetFramework="4.0">

我收到“无法从用法推断类型参数”错误。另一个工作类似但不使用标准助手的助手工作正常。我也试过这个:

@{ Html.FormLine<ViewModel, string>(model => model.FirstName); }

这会给出错误“无法将类型 'string' 隐式转换为 'string[]'”。

我看到了类似的问题,但我无法找到答案。那我做错了什么?

【问题讨论】:

    标签: c# asp.net-mvc-3 razor helper inference


    【解决方案1】:

    为什么要得到属性数组?

    如何改变这一行:

    Expression<Func<TModel, TProperty[]>> expression,
    

    Expression<Func<TModel, TProperty>> expression,
    

    【讨论】:

    • 啊该死的,这是一个鬼鬼祟祟的小错误。我完全阅读了这一点。我对这些事情视而不见。确实可以使用@(Html.FormLine&lt;ViewModel, string&gt;(model =&gt; model.FirstName)) 谢谢!
    • 当然现在它也可以这样工作:@Html.FormLine(model =&gt; model.FirstName)
    猜你喜欢
    • 2012-03-20
    • 2014-12-02
    • 2011-09-06
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2014-10-19
    相关资源
    最近更新 更多