2012-10-30 18 views
2

我有某种形式的一个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"> 

我得到的错误“之类参数不能从使用推断”。另一个作品similair,但不使用标准助手的助手工作正常。我也试过这样:

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

这给错误“无法隐式转换类型‘字符串’到‘字符串[]’”。

我见过similair问题,但我一直没能找到答案。那么我做错了什么?

回答

1

为什么你会得到属性的阵列?

如何改变这一行:

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

随着

Expression<Func<TModel, TProperty>> expression, 
+0

啊该死这是一个狡猾的小错误。我完全阅读了。我盯着这些东西瞎了眼。这确实使用'@(Html.FormLine (model => model.FirstName))' 谢谢! – PeterB

+0

现在它也可以这样工作:'@ Html.FormLine(model => model.FirstName)' – PeterB