2016-06-22 29 views
-1

我是新來的MVC,嘗試創建一個簡單的用戶界面時出現問題。我必須在視圖中顯示模型並支持分頁。 我的視圖將顯示每列,並在列的名稱下方必須有文本框或下拉以執行數據過濾。查看沒有迭代IEnumerable模型C#

我的模型是如下

public class ViewModel : ViewModelBase 
{ 
    public long Id { get; set; } 

    [DisplayName("Name")] 
    public string Name{ get; set; } 

    [DisplayName("Full Name")] 
    public string fullName{ get; set; } 

    [DisplayName("State")] 
    public string adressState{ get; set; } 

    [DisplayName("Grade")] 
    public string grade{ get; set; } 

    public MultiSelectList grades{ get; set; } 
    public MultiSelectList adressState{ get; set; } 
    } 

我傳遞了IEnumerable模型查看和我的看法應該是如下

<div class="dataTable"> 
<table id="mainTable"> 
    <thead> 
     <tr > 
      <th ></th> 
       @Html.HiddenFor(model => model.Id) 
      <th> 
       @Html.DisplayNameFor(model => model.Name) 
      </th> 
      <th> 
       @Html.DisplayNameFor(model => model.fullName) 
      </th> 
      <th> 
       @Html.DisplayNameFor(model => model.address) 
      </th> 
      <th> 
       @Html.DisplayNameFor(model => model.grade) 
      </th> 
     </tr> 
     <tr > 
      <th> 
       <img src="~/Images/someimage.png" alt="Options" height="25" width="25" /> 

      </th> 
       @Html.HiddenFor(model => model.Id) 
      <th> 
       @Html.TextBoxFor(model => model.name, new { onkeyup = "handleKeyPress(event, this)", placeholder = "Search", @class = "TextBox searchProperties" }) 
      </th> 
      <th> 
       @Html.TextBoxFor(model => model.fullName, new { onkeyup = "handleKeyPress(event, this)", placeholder = "Search", @class = "TextBox searchProperties"}) 
      </th> 
      <th> 
       @Html.ListBoxFor(model => model.adressState, Model.adressStateItemList as MultiSelectList, new { onchange = "handleDropdownChange()", @id = "adressStateDropDown", 
       @class = "searchProperties" }) 

      </th> 
      <th> 
       @Html.ListBoxFor(model => model.gradeItem, Model.gradeItemList as MultiSelectList, new { onchange = "handleDropdownChange()", @id = "gradeDropDown", 
       @class = "searchProperties" }) 
      </th> 
     </tr> 
    </thead> 
    <tbody id="tableResults"> 
     @{Html.RenderPartial("_StudentPartial", Model);} 
    </tbody> 
</table> 

學生部分必須有一個通過每個循環模型數據和顯示。 我無法綁定我的模型來查看和顯示數據,因爲我的主視圖需要模型顯示屬性的文本框,並且部分視圖需要IEnumerable模型。我試過 @ Html.Partial(「_ studentPartial」,新IEnumerable <。解決方案.ViewModel>) 但無效。有人可以提出解決方案嗎?

+2

如果所顯示的視圖有*單個實例*的東西的模型,你怎麼能指望派生的東西*列表*?你可以把一籃蘋果變成單個的蘋果,但是你不能把一個蘋果變成一籃子蘋果。另外,你不能創建* interface *的new實例,只能創建一個* class *。 – David

+0

您正在顯示的視圖意味着該模型是單個實例,而不是集合。如果模型是一個集合,爲什麼你需要將它轉換爲內部視圖中的集合?這沒有任何意義。 – David

+0

如果模型是一個集合,那麼這個視圖中的任何HTML幫助器如何工作?似乎還有對屬性的引用,這些屬性甚至都不在模型上,並且模型似乎具有多個屬性,並且具有相同的名稱。由於多種原因,此代碼甚至無法編譯。您可能需要備份一些並返回到一些MVC教程。 – David

回答

0

如果部分視圖的目的是顯示單個項目,則不應將該部分視圖綁定到IEnumerable。它應該綁定到單個模型實例。

如果主視圖綁定到IEnumerable<ViewModel>,則將該部分綁定到ViewModel

在主視圖

然後,

foreach(var item in Model) 
{ 
    @{Html.RenderPartial("_StudentPartial", item);} 
}