1
votes

I am trying to add a partial view to my MVC4 web application and I receive the following exception:

The model item passed into the dictionary is of type '...Meeting', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[...UserProfile]'.

what I did so far:

  1. i added to my controller this function:
public PartialViewResult GetUsers()
        {
            var usersList = (from users in db.Users select users).ToList();
            return PartialView(usersList);
        }
  1. I added the parital view:
@model List<UserProfile>
@{
 <select id="Meeting_SetToUser" name="Meeting.SetToUser">
        @foreach (var item in Model)
        {
            <option value="@item.UserId">@item.FirstName @item.LastName</option>
        }
    </select>
}
  1. i called the partialview from my view:
@Html.Partial("GetUsers")

can you please direct me to were I am doing anything wrong?

Thank you!

2
my partialView type is List<UserProfile> I also inspected my controller's method and I am sending the same type to the partialView. - Shlo
@Shlo, but where are you calling the GetUsers action? - Darin Dimitrov
I guess this way it is never called as you answered here... changing to Action solved the problem. next time I will try also a breakpoint and see if I reach the method or not. Thanks. - Shlo
I mean the View which the PartialView belongs to. You never call your Action. With line @Html.Partial("GetUsers") you just render the PartialView and pass the View's Model to it, not List<UserProfile>. - Zabavsky
thank you @Zabavsky I understand my problem. I switched to Action. - Shlo

2 Answers

2
votes

The GetUsers action doesn't seem to ever be called when you use Html.Partial. Maybe you wanted to use a child action:

@Html.Action("GetUsers")

Checkout the following article to better understand the difference between Html.Partial and Html.Action.

Also generating a dropdown list using a foreach loop instead of using the Html.DropDownList helper seems quite inappropriate. Maybe you wanted to use this helper, didn't you:

@model List<...UserProfile>
@Html.DropDown(
    "Meeting.SetToUser", 
    new SelectList(
        Model.Select(x => new 
        { 
            UserId = x.UserId, 
            FullName = string.Format("{0} {1}", x.FirstName, x.LastName) }
        ),
        "UserId", 
        "FullName"
   )
)

I would also very strongly recommend you using view models instead of passing your domain models to the views.

0
votes

See closely GetUsers() action, You are passing model of type List to partial view where as partial view accepts type List<...UserProfile>.

The resolutions is to send a proper type what partial view is accepting.