2016-03-28 69 views
1

我在页面上有一个MVC WebGrid,每行都有我的网格选择链接。在同一视图中,我希望获取与该对象关联的模型对象并在视图内使用它。如何从同一视图中使用MVC WebGrid的SelectedRow对象?

我发现访问SelectedRow对象的每个示例都提供了有关如何使用对象将对象传递到其他视图/局部视图的说明。在我的情况下,我想从WebGrid的相同视图中访问此对象。

以下是一些通用示例代码,其中包含与错误相关的注释。

@{ 

    var grid = new WebGrid(dataCollection) 
    @grid.GetHTML(columns: "ID", "User ID"), 
     grid.Column("UserName","Name"), 
     grid.Column("", format: @<text>@item.GetSelectLink("Edit")</text>) 
} 

<!-- FURTHER DOWN IN MY MARKUP //--> 

<div class="widget"> 
@if(grid.HasSelection) 
{ 
    var obj = @grid.SelectedRow; 

    //The example below reports the following error when 
    //navigating to this page: 
    // 
    //CS0039: Cannot convert type 
    // 'System.Web.Helpers.WebGridRow' to 
    // 'Models.User' via a reference 
    // conversion, boxing conversion, unboxing conversion, 
    // wrapping conversion, or null type conversion 
    usr = obj as User; 
    if (usr != null) <text>usr.ID</text>; 
     <!-- FIND A WAY TO PRINT SELECTED CONTENT --> 
} 
</div> 

我也试过铸造声明,如((User)@grid.SelectedRow)。在这种情况下,页面会加载,但只要我尝试选择一条记录并且上面的行被打中,浏览器就会给我不同但相似的错误。

如何在与我的WebGrid相同的视图中访问和使用WebGrid.SelectedRow模型对象?

回答

1

我希望以下答案能帮助你。它会显示选定的行内容

@{ 
    List<Person> person = new List<Person>(); 
    person.Add(new Person { PersonCode = "1001", PersonName = "Satya Nadella" }); 
    person.Add(new Person { PersonCode = "1002", PersonName = "Lisa Su" }); 
    person.Add(new Person { PersonCode = "1003", PersonName = "Jeff Clarke" }); 
    person.Add(new Person { PersonCode = "1004", PersonName = "Mark Fields" }); 
    person.Add(new Person { PersonCode = "1005", PersonName = "Phebe Novakovic" }); 
    person.Add(new Person { PersonCode = "1006", PersonName = "Mary T. Barra" }); 
    person.Add(new Person { PersonCode = "1007", PersonName = "Rajeev Suri" }); 
    person.Add(new Person { PersonCode = "1008", PersonName = "Michel Combes" }); 
} 

@{ 
    WebGrid grid = new WebGrid(person, rowsPerPage: 10); 

    @grid.GetHtml(columns: grid.Columns(grid.Column("PersonCode", "Code"), grid.Column("PersonName", "Name"), grid.Column("", format: @<text>@item.GetSelectLink("Edit")</text>))) 
} 

<div> 
    @if (grid.HasSelection) 
    { 
     if (grid.SelectedRow != null) 
     { 
      <div> 
       Code: @grid.SelectedRow.Value.PersonCode 
      </div> 
      <div> 
       Name: @grid.SelectedRow.Value.PersonName 
      </div> 
     }   
    } 
</div> 
+0

这个工作。我不知道“价值”属性。在代码中放置断点,并检查内存中的值暗示着不同的东西。特别是'SelectedRow'对象应该是我的模型对象。谢谢。 – RLH

相关问题