pass a different model to the partial view

user3541362 picture user3541362 · May 11, 2014 · Viewed 41.5k times · Source

I am trying to pass a different model to the partial view from a view. I have two separate controller actions for both of them and two different view models. But when I call the partial view from within the view it gives me the error

The model item passed into the dictionary is of type 'Application.ViewModels.Model1ViewModel', but this dictionary requires a model item of type 'Application.ViewModels.PartialViewModel'.

I am calling it like this:

 @Html.Partial("_CreateUniFunctionPartial")

the model call in the view is

@model Application.ViewModels.Model1ViewModel

and model in partial view file is

@model Application.ViewModels.PartialViewModel

I am not sure how to pass the partial view so it doesnt give this error.

EDIT

Partial view

@model Application.ViewModels.PartialViewModel



 @using (Html.BeginForm("partialview", "ApplicationDetail", FormMethod.Post)) 
  {


<div class="form-horizontal">
    <h4>UniFunctionViewModel</h4>
    <hr />
    @Html.ValidationSummary(true)





    <div class="form-group">
        @Html.LabelFor(model => model.detail, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.detail, new { @placeholder = "Further Information" })
            @Html.ValidationMessageFor(model => model.detail)
        </div>
    </div>


</div>

}

Answer

alexo picture alexo · Jun 28, 2014

you are using the right method but not passing in the right arguments

you might want to try it like this:

@Html.Partial("~/[path_to_root_only_if_exists]/_CreateUniFunctionPartial.cshtml", new Application.ViewModels.PartialViewModel())

if you do not pass in a model, it will automatically take the one from its parent, which in your case is

Application.ViewModels.Model1ViewModel