Search code examples
c#asp.net-mvc-3razorhelperinference

"The type arguments cannot be inferred from the usage" in view with custom helper using standard helper


I've got some forms for an MVC3 website with alot of repeating parts. So I tried to make a helper for this. Following an example form the internet i made this:

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());
        }
    }
}

This compiles just fine. However when i do

@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>

I made sure the web.config contains

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

I get the "The type arguments cannot be inferred from the usage" error. Another helper that works similair, but doesn't use the standard helpers works fine. I have also tried this:

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

Which gives the error "Cannot implicitly convert type 'string' to 'string[]'".

I have seen similair questions but I haven't been able to find an answer. So what am i doing wrong?


Solution

  • Why you get the array of properties?

    How change this line:

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

    With

    Expression<Func<TModel, TProperty>> expression,