Reputation: 55
I'm new to web API, and all the examples are in C# which doesn't help, as such I've hit a roadblock early on. I'm returning data from SQL, putting it an object array list, and then trying to return it so it could be read by a JSON client.
This is my default GET on my controller:
Function Index() As IEnumerable(Of String)
Dim Sites As New ArrayList
Dim dt As DataTable = DataLayer.ExecuteNoParamStoredProcedure("stored_proc", "connection_string")
For Each r As DataRow In dt.Rows()
Sites.Add(New SiteDetails(r("SiteName"),r("SiteId")))
Next
Return Sites
End Function
And here is my SiteDetails class:
Public Class SiteDetails
Public site As String
Public siteid As String
Public Sub New(sitename As String, id As String)
site = sitename
siteid = id
End Sub
End Class
Questions: How to I make it output the data on the page in a format that isn't either an error or just the object name? Is there a better way to do what I'm doing?
Joe
EDIT just to comment, the above doesn't work from the off, because it can't the return type (IEnumerable(Of String)) doesn't allow an arraylist to be returned, this is the bulk of my issue.
Upvotes: 2
Views: 1877
Reputation: 22436
In your sample, you return an IEnumerable(Of String)
. Therefore, when returning the result of your action method, all objects are converted to a string by calling the ToString
method (I suspect you have OPTION STRING turned OFF in your project); in your case, the default implementation of ToString
is used. This implementation returns the name of the type.
In order to return the data, I'd change the code as follows:
Function Index() As IEnumerable(Of SiteDetails)
ToString
method of the SiteDetails class so that the required data are formatted as a string correctly.In addition, I'd propose not to use the ArrayList
class anymore; there is a strongly typed List(Of T)
class (in your case List(Of SiteDetails)
if you want to return the SiteDetails objects or List(Of String)
if you want to return strings).
Also, make sure that you are using a Web API controller. These controllers are derived from the ApiController
class (as opposed to a MVC controller that looks roughly the same, but is derived from System.Web.Mvc.Controller
).
Upvotes: 1