VB.net传递强类型模型w / List要查看

时间:2012-12-24 14:48:12

标签: asp.net-mvc vb.net

立即学习ASP.NET,VB.Net,MVC 我的目的是将模型传递给视图。 我有一个简单的字符串案例的成功测试代码。 我认为我今天磕磕绊绊的地方在于当前的viewmodel是一个对象列表。 我得到的错误是“传入字典的模型项的类型为'MVC_Test1.Geocode_Google_Results []',但此字典需要类型为'MVC_Test1.Geocode_Google_Results'的模型项。” 因此,由于我的理解有限,我似乎传递了一个对象列表(按预期),但视图模型类型是用于创建列表的简单对象类型。

在一些例子中,回复是在C#中。这些都集中在For Each方法(这是我第一个如何使这项工作的概念)。 我试过这个但最后在For Each ... AS对象子句中出现了对象类型错误。

我找到了一个www示例,表明它应该像数组一样接近: 对于I,整数= 0到Model.Results.Count 这使我可以构建代码,但在运行时而不是构建时会导致上面提到的对象类型错误。

继续阅读,有几个主题似乎调用@model IEnumerable作为一种方法。这样做只会使viewdata和model对象在完成时未定义:

     @Modeltype IEnumberable MVC_Test1.Geocode_Google_Results

     @Model IEnumberable MVC_Test1.Geocode_Google_Results

我怀疑有一些简单/基础我应该知道这一切都可以。这似乎是设计问题的直接前提,没有一个构造良好的答案。

如果答案可以在VB.net的上下文中解释,那对我来说会更有帮助。我确实使用其中一个Web C#到VB.net转换器来翻译,所以任何响应都比没有好。

谢谢,

以下详细信息:

我有一个简单的课程:

Public Class Geocode_Google_Results
    Public Property Results As New List(Of ManyGeocodeCoordinates)
    'Methods
    'Add to list
    Public Sub AddResults(Address, Latitude, Longitude)
        Results.Add(New ManyGeocodeCoordinates() With {.Address = Address, .latitude = Latitude, .longitude = Longitude})
    End Sub
End Class

Public Class ManyGeocodeCoordinates
     Public Property Address As String
     Public Property latitude As Double
     Public Property longitude As Double
End Class

然后我填充了一些数据:

    For x As Integer = 1 To resultCount
        ManyResults(x) = New Geocode_Google_Results
        ManyResults(x).AddResults(results.Elements("result").Elements("formatted_address").Value, results.Elements("result").Elements("geometry").Elements("location").Elements("lat").Value, results.Elements("result").Elements("geometry").Elements("location").Elements("lng").Value)

    Next

然后我转到视图:

    ElseIf resultCount = 1 Then
        ' Send the user to the results page...Default View Page
        Return View(ManyResults)

然后我有一个测试视图:

@Modeltype MVC_Test1.Geocode_Google_Results
@Code
    ViewData("Title") = "httptest"
End Code

<h2>httptest</h2>
Default single address view
@model.Results(0).Address   <br />
@model.results(0).latitude <br />
@model.results(0).longitude <br />

在IE中运行时,我得到关于对象列表与模型类型对象的错误提示。

1 个答案:

答案 0 :(得分:1)

继续阅读并在这里进行实验是我找到的。

viewmodel(class)是一个单数对象。当我用数据填充类的实例时,我使用数组表示法无疑是从对象数组上下文中绘制的。但是,该类不是对象数组。该功能由作为对象列表的属性提供。

因此,将数据分配为Manyresults(x)是不正确的。

需要将数据指定为

ManyResults.AddResults(results.Elements("result").Elements("formatted_address").Value, results.Elements("result").Elements("geometry").Elements("location").Elements("lat").Value, results.Elements("result").Elements("geometry").Elements("location").Elements("lng").Value)

同样地,在视图中,模型数据的格式为:

@Model.Results(0).Address

在我的示例中,当返回多个结果时,将使用Model.Results(n).Address,其中n是您要查找的结果维度。 Model.results.count将用于确定视图模型中有多少结果。

相关问题