2013-05-15 66 views
0

我有一個局部視圖,它在兩個不同的視圖上進行。這兩個不同的視圖使用不同的視圖模型。在視圖中的一個的代碼是:在兩個視圖上使用局部視圖

廠景:

@model StudentsViewModel 
...... 
..... 
@Html.Partial("_StudentOtherInformation") 

PartialView

@model StudentsViewModel 
@if (Model.StudentList != null) 
{ 
<input type="hidden" id="firstStudent" value= "@Model.StudentList.ElementAt(k-1).StudentID" /> 
} 

視圖2:

@model SearchViewModel 
.... 
@Html.Partial("_StudentOtherInformation") 

正如從上面的代碼局部視圖需要訪問視圖模型view1。我得到異常說partialview與viewmodel混淆。我做了一些研究,發現單方面是創建一個包含兩個視圖模型的parentviewmodel。但問題是兩個viemodel在不同的命名空間中。有沒有什麼辦法可以將各自的視圖模型從每個視圖傳遞給partialview?

回答

1

您可以將您的視圖模型作爲第二個參數:

廠景:

@model StudentsViewModel 
...... 
..... 
@Html.Partial("_StudentOtherInformation", model) 

視圖2:

@model SearchViewModel 
.... 
@Html.Partial("_StudentOtherInformation", model) 

然而,這並不讓你通過兩種不同類型。

你可以做的只是創建一個基類,把公共屬性放在那裏,並從這個基類繼承你的兩個ViewModel。它們在不同的命名空間中是沒有問題的。你只需要引用正確的命名空間:

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 
} 

你的部分觀點應該然後是強類型的基類:

PartialView

@model ParentViewModel 
@if (Model.StudentList != null) 
{ 
<input type="hidden" id="firstStudent" value= "@Model.StudentList.ElementAt(k-1).StudentID" /> 
} 
+0

所以,我應該通過Parentviemodel到這兩種觀點還是他們自己的觀點? – user1032957

+0

伴侶,我碰到一些閱讀使用接口這種問題....公共字符串getFirstStudent()在每個使用局部視圖的viemodel。那麼,有沒有實現這個想法? – user1032957

+0

當然,這將是相同的概念,您只需用接口替換基類即可。唯一的區別是您必須在兩個ViewModel上實現這些屬性 – Kenneth