ASP.NET MVC Runtime Compiler Complains About Wrong Model Type when Model is Null

I have a strange problem with ASP.NET MVC 4 Partial Views, when their models are null. Everything works fine when model is not null. The runtime compiler warning is

The model item passed into the dictionary is of type 'LoyalisticSuite.Models.SignUpStartInfo', but this dictionary requires a model item of type 'LoyalisticSuite.Code.CustomerInfo'.

On my layout page, I call them as follows:

@Html.Partial("_TelephoneNotification", Session["Customer"])

where Session["Customer"] is indeed of type of CustomerInfo. The view is declared as follows:

@using MVC.Common.Extensions
@model LoyalisticSuite.Code.CustomerInfo

@if (Model != null && string.IsNullOrWhiteSpace(Model.Telephone) && Model.Owner != null && Model.Owner.Value == (Guid)Membership.GetUser().ProviderUserKey)
{
    <div id="customerInfoNotification" class="privacy-policy-notification" style="display: none;">
        ... cut off some markup ...
    </div>
}

Why is the runtime compiler interpreting null as some random type, here 'LoyalisticSuite.Models.SignUpStartInfo'? Everything works fine for non-null values. What is the problem, and how can I remedy it? Has anyone else encountered this problem?

Thanks for all help in advance!


I ended up in creating a following simple wrapper struct:

public struct Single<T>
{
    public Single(object value) : this()
    {
        Value = (T) value;
    }

    public T Value { get; set; }
}

Now, I can pass the value without having to deal with nulls as follows:

@Html.Partial("_TelephoneNotification", new Single<CustomerInfo>(Session["Customer"]))

And declare the Partial View Model as:

@model MVC.Common.Single<LoyalisticSuite.Code.CustomerInfo>
@if (Model.Value != null && string.IsNullOrWhiteSpace(Model.Value.Telephone) && Model.Value.Owner != null && Model.Value.Owner.Value == (Guid)Membership.GetUser().ProviderUserKey)
{
    ...
}
链接地址: http://www.djcxy.com/p/59764.html

上一篇: 在MVC视图模型中是错误的吗?

下一篇: ASP.NET MVC运行时编译器抱怨模型为空时的错误模型类型