0

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?

1 Answer 1

1

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" />
}
Sign up to request clarification or add additional context in comments.

3 Comments

so, should I pass Parentviemodel to the two views or their own viemmodels?
Mate, I came across some reading to use Interface for this kind of problem.... public string getFirstStudent() on every viemodel that makes use of the partial view. So, any idea of implementing that?
Sure, it would be the same concept, you just replace the base-class with the interface. The only difference is that you'd have to implement the properties on both ViewModels

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.