MVC View: Type arguments Html helper DisplayFor ca

2020-04-05 19:30发布

问题:

I'm trying to make use of the extended HTML Helper DisplayFor in this View:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcCms.Web.ViewModels.SubscriptionsViewModel>" %>

<% using (Html.BeginForm("TrainingSubscription", "Account", FormMethod.Post))
    { %>
 <%: Html.DisplayFor(m => m.Subscriptions) %>
 <input type="submit" value="Save" />
 <% } %>

with the following ViewModel

namespace MvcCms.Web.ViewModels
{
    public class SubscriptionsViewModel
    {
        public string TrainingId { get; set; }
        public string Subject { get; set; }      
        public IEnumerable<SubscriptionViewModel> Subscriptions { get; set; }

        public SubscriptionsViewModel(string TrainingId, string Subject, IEnumerable<SubscriptionViewModel> Subscriptions)
        {
            this.TrainingId = TrainingId;
            this.Subject = Subject;
            this.Subscriptions = Subscriptions;
        }
    }

    public class SubscriptionViewModel
    {
        public string ContactId { get; set; }
        public string FullName { get; set; }
        public bool Subscribed { get; set; }

        public SubscriptionViewModel(string ContactId, string FullName, bool Subscribed)
        {
            this.ContactId = ContactId;
            this.FullName = FullName;
            this.Subscribed = Subscribed;
        }
    }
}

It's giving me this error

The type arguments for method 'System.Web.Mvc.Html.DisplayExtensions.DisplayFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly

I can't figure what's wrong. Note that I'm able to access the Model in a strongly typed manner with IntelliSense popping up in the view. However, IntelliSense is not popping up when I'm typing the lambda-expression.

回答1:

I got it working now, the problem was that the project still compiled with .NET v3.5 instead of v4.0, see:

https://stackoverflow.com/a/7142200/1232507