Reputation: 473
I have a Partialview which goes on two differnet views. The two different views use differnet viewmodels. On one of the view the code is:
view1:
@model StudentsViewModel
......
.....
@Html.Partial("_StudentOtherInformation")
PartialView
@model StudentsViewModel
@if (Model.StudentList != null)
{
<input type="hidden" id="firstStudent" value= "@Model.StudentList.ElementAt(k-1).StudentID" />
}
view2:
@model SearchViewModel
....
@Html.Partial("_StudentOtherInformation")
As from the above code partial view needs to access viewmodel of view1. Im getting exception saying that partialview is getting confused with viewmodel. I did some research and found oneway is to create a parentviewmodel containing two viewmodels. But the problem is the two viemodels are in different namespaces. Is there any way I can pass the respective viewmodel to partialview from each of the views?
Upvotes: 0
Views: 145
Reputation: 28747
You can pass your ViewModel as the second argument:
view1:
@model StudentsViewModel
......
.....
@Html.Partial("_StudentOtherInformation", model)
view2:
@model SearchViewModel
....
@Html.Partial("_StudentOtherInformation", model)
However, this doesn't allow you to pass two different types.
What you could do is just make a base class, put the common properties in there and inherit your two ViewModels from this base class. It's no problem that they are in different namespaces. You just need to reference the correct namespaces:
public class ParentViewModel
{
public List<Student> StudentList{ get; set; }
}
public class StudentsViewModel : your.namespace.ParentViewModel
{
// other properties here
}
public class SearchViewModel: your.namespace.ParentViewModel
{
// other properties here
}
Your partial view should then be strongly typed to the base-class:
PartialView
@model ParentViewModel
@if (Model.StudentList != null)
{
<input type="hidden" id="firstStudent" value= "@Model.StudentList.ElementAt(k-1).StudentID" />
}
Upvotes: 1