0

I am developing an ASP.Net MVC 3 web application. I have a ViewModel

public class ViewModelFormPreview
{
    public FormPersonal PersonDetails { get; set; }
    public IList<FormEmployment> Employment { get; set; }
    public FormMembership Membership { get; set; }
}

And a Razor View which accepts this ViewModel

@model Locum.UI.ViewModels.ViewModelFormPreview

<h1 class="sepH_b">Application Preview</h1>

  @Html.Partial("FormPreviewApplication/PersonalDetails", Model.PersonDetails)

  @Html.Partial("FormPreviewApplication/Employment", Model.Employment)

  @Html.Partial("FormPreviewApplication/MembershipDetails", Model.Membership)   

The last part of the View is where my problem is happening.

If Model.Memebership != null then the Partial View, which accepts an Object of type FormMembership, works nicely. However, if Model.Memebership is NULL, I get an error like below

The model item passed into the dictionary is of type 'Locum.UI.ViewModels.ViewModelFormPreview', but this dictionary requires a model item of type 'Locum.POCO.FormMembership

This is a strange error, because, even if Model.Memebership is NULL, it is still of type FormMembership. So then, why is the error stating I am trying to pass in ViewModelFormPreview when the Object is NULL?

Can anyone help with this?

Thanks.

2 Answers 2

2

As the message says, it is NULL and not EMPTY. If you try to use Membership.MyFiels, with membership null, you always get an error.

To resolve your problem simply initialize your class, with default values in case of NULL, or use an IF to check if it's NULL or not

Something like this.

@if (Model,Membership!=null) {
  @Html.Partial("FormPreviewApplication/MembershipDetails", Model.Membership) 
}
else
{
  @Html.Partial("FormPreviewApplication/MembershipDetails", new FormMembership())     
}
Sign up to request clarification or add additional context in comments.

3 Comments

While this works, it's putting logic into your Views which you should avoid. IMO it would be better to have a param-less constructor for your ViewModel which defines new instances of each parameter by default. +1 anyway for the fix.
@RoryMcCrossan Fair point Rory. I might look into this option also. Cheers.
I agree, the first part of my answer was to mean that. To put the initialization code in the ctor of the ViewModel or in the controller is up to you. Personally I prefer to use the ViewModel as pure DTOs, but as usual is a matter of taste :)
1

Can you create a new empty Membership class instance and pass to partial to avoid this error

1 Comment

I could, but I am looking for another solution. Thanks though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.