I am trying to get the following to work
Function AddService(id As Integer) As ViewResult
Dim serv As RequestedService = New RequestedService
serv.JobId = id
Dim ServiceList = New List(Of RequestedService)()
Dim ServiceQuery = From s In db.Services
Select s
ServiceList.AddRange(ServiceQuery)
ViewBag.ServiceId = New SelectList(ServiceList, s.IDServices, s.ServiceName)
Return View(serv)
End Function
But
ViewBag.ServiceId = New SelectList(ServiceList, s.IDServices, s.ServiceName)
Gives me the following error: 's' is not declared. It may be inaccessible due to its protection level.
I cannot work out how to correct this. Essentially I need to populate the SelectList with both an id and string and pass it to the view?
Assuming that the RequestedService model has properties called IDServices and ServiceName you could use the following:
ViewBag.ServiceId = New SelectList(ServiceList, "IDServices", "ServiceName")
But you really don't need this intermediary list:
Function AddService(id As Integer) As ViewResult
Dim serv As RequestedService = New RequestedService
serv.JobId = id
ViewBag.ServiceId = New SelectList(db.Services, "IDServices", "ServiceName")
Return View(serv)
End Function
And you really, really, really don't need to use ViewBag, but use view models instead.
Function AddService(id As Integer) As ViewResult
Dim model = New RequestedServiceViewModel
model.JobId = id
model.Services = New SelectList(db.Services, "IDServices", "ServiceName")
Return View(model)
End Function
and now your view is strongly typed to the view model:
#ModelType RequestedServiceViewModel
#Html.DropDownListFor(Function(x) x.ServiceId, Model.Services)
Related
I am new to .Net framework and I am getting an error message
Value of type 'List(Of AdminSetEmployeeParams)' cannot be converted to
'AdminSetEmployeeParams'"
Dim SetNewEmployee As New List(Of AdminSetEmployeeParams)
SetNewEmployee.Add(New AdminSetEmployeeParams With {
.departmentId = ddlDept.SelectedValue,
.familyName = txtLastOrSurname.Text,
.firstName = txtFirstOrGivenName.Text,
.secondName = txtSecondName.Text,
.contactPhone = txtPhone.Text,
.user = ""})
SetNewEmployee = EmployeeAPIService.AdminSetEmployee(SetNewEmployee).Result
How would I resolve this error?
Update:
System.Threading.Tasks
Public Class Task(Of TResult)
Public ReadOnly Property Result As TResult
It's probably this, but it's hard to be sure:
Dim newEmployee As New AdminSetEmployeeParams
newEmployee = New AdminSetEmployeeParams With {
.departmentId = ddlDept.SelectedValue,
.familyName = txtLastOrSurname.Text,
.firstName = txtFirstOrGivenName.Text,
.secondName = txtSecondName.Text,
.contactPhone = txtPhone.Text,
.user = ""})
Dim newEmployeeResult As List(Of AdminSetEmployeeParams) = EmployeeAPIService.AdminSetEmployee(newEmployee).Result
I'm not sure why your API returns a list of employees in its result (I'm assuming it does because you don't say you have an error message complaining about the assignment of the result to a list(of...) ) but the error as given would reasonably only occur if the API call demanded a single new employee and you handed it a list of new employees
If it doesn't work out, try this last line
Dim newEmployeeResult As AdminSetEmployeeParams = EmployeeAPIService.AdminSetEmployee(newEmployee).Result
And if that doesn't work out, edit your question to give more info on what kind of arguments AdminSetEmployee takes and what kind of object .Result is
I am trying to follow this video that is written in C# and convert it to vb (to Populate a dropdown box from SQL Server using a function)
here is the working C# code:
private list<product> getallprodcuts()
{
Try
{
using(PropSolWebDBEntities db= new PropSolWebDBEntities())
list<product> products = (from x in db.product select x).tolist;
}
catch(exception)
{
Return Null;
}
}
And the vb that I cant get to work:
Private Function getallproducts() As List( Of<product>)
Try
Dim db As New PropSolWebDBEntities
Dim products As list <product> = (from x in db.product select x).tolist
Return products
Catch ex As Exception
Return vbNull
End Try
End Function
What am I doing wrong?
List should be translated as List(of product).
return null should be translated as Return Nothing.
Use using instead of declaring the db variable.
I don't compile the code, but it's like this:
Private Function getallproducts() As List(Of product)
Try
Using db As New PropSolWebDBEntities
Dim products As list(Of product) = (From x In db.product Select x).ToList()
Return products
End Using
Catch ex As Exception
Return Nothing
End Try
End Function
You don't need the LINQ part since you are not filtering/grouping/ordering by. The Using block takes care of your context disposal for you. You just missed some syntax difference.
Private Function getallproducts() As List(Of product)
Dim results As List(Of product) = Nothing
Using db As New PropSolWebDBEntities
results = db.product.ToList
End Using
Return results
End Function
Hi i am trying to sum all my datatable values to one row. but i retrieve a InvalidCastException:
Failed to convert an object of
typeWhereSelectEnumerableIterator2[System.Linq.IGrouping2[System.Object,System.Data.DataRow],VB$AnonymousType_0`4[System.Object,System.Double,System.Decimal,System.Decimal]]
to type System.Data.DataTable.
SQL Datatypes:
NAME_AGE string
LON money
sal_tjformon money
sal_sjuklon money
Private Function GroupByName(dataTable As DataTable) As DataTable
Dim result = dataTable.AsEnumerable().GroupBy(
Function(row) row.Item("NAME_AGE")).Select(Function(group) New With {
.Grp = group.Key,
.LON = group.Sum(Function(r) Decimal.Parse(r.Item("LON"))),
.sal_tjformon = group.Sum(Function(r) Decimal.Parse(r.Item("sal_tjformon"))),
.sal_sjuklon = group.Sum(Function(r) Decimal.Parse(r.Item("sal_sjuklon")))
})
Return result
The LINQ statement returns an IEnumerable(Of <anonymous_type>). There are two problems with this. First of all, your function returns a DataTable, which your object definitely is not. Secondly of all, you can't return an anonymous type from a function call.
If you want to return the select result, you have to create an explicit type (a class) and return the IEnumerable(Of MyType), like in the code below. I strongly advice to set an explicit type to the Grp property (like String?).
Class GroupNameAgeResult
Public Property Grp As Object
Public Property LON As Decimal
Public Property sal_tjformon As Decimal
Public Property sal_sjuklon As Decimal
End Class
Private Function GroupByName(dataTable As DataTable) As IEnumerable(Of GroupNameAgeResult)
Dim result = dataTable.AsEnumerable().GroupBy(Function(row) row.Item("NAME_AGE")) _
.Select(Function(grp) New GroupNameAgeResult() With
{.Grp = grp.Key,
.LON = grp.Sum(Function(r) Decimal.Parse(r.Item("LON").ToString)),
.sal_tjformon = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_tjformon").ToString)),
.sal_sjuklon = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_sjuklon").ToString))})
Return result
End Function
If you want to return a DataTable, you can define this, loop over the groups and add a row. You can return afterwards the result. See example code below.
Private Function GroupByName(dataTable As DataTable) As DataTable
Dim result As New DataTable()
result.Columns.Add("Grp", GetType(Object))
result.Columns.Add("LON", GetType(Decimal))
result.Columns.Add("sal_tjformon", GetType(Decimal))
result.Columns.Add("sal_sjuklon", GetType(Decimal))
For Each grp In dataTable.AsEnumerable().GroupBy(Function(row) row.Item("NAME_AGE"))
Dim row As DataRow = result.NewRow()
row.Item("Grp") = grp.Key
row.Item("LON") = grp.Sum(Function(r) Decimal.Parse(r.Item("LON").ToString))
row.Item("sal_tjformon") = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_tjformon").ToString))
row.Item("sal_sjuklon") = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_sjuklon").ToString))
result.Rows.Add(row)
Next
Return result
End Function
Last but not least. I strongly advice you to turn on "Option strict" (you can set this in the project properties -> Compile). You'll notice many more (possible) errors with your code (even the small function from this question).
I'm trying to sort a list of tweets (class: SimpleTweet), which each have ID associated with them (x.ID where x is an object of class SimpleTweet). I'm using linq to sort this, using "OrderByDescending", but am getting an error on the line where I set a new object of type List(Of SimpleTweet) equal to the sorted list. The error I am getting is, "System.InvalidCastException: Unable to cast object of type 'System.Linq.OrderedEnumerable2[SimpleTweet,System.Int64]' to type 'System.Collections.Generic.List1[SimpleTweet]'".
The code:
<WebMethod()> _
Public Function GetTweetsByUserID(ByVal userID As Integer) As List(Of SimpleTweet)
Dim result As New List(Of SimpleTweet)
Dim urlTwitter As String = "https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&screen_name={0}&count=3"
'Dim twitterfeed As String = utils.GetUserTwitterFeeds(userID, "docphin")
Dim lq As New lqDFDataContext
Dim var = lq.web_GetTweetsByUserID(userID).ToList()
Dim sortedresult As New List(Of SimpleTweet)
If Not var Is Nothing Then
For Each twitterfeed In var
Dim listURL As String = String.Format(urlTwitter, twitterFeed.TweeterFeed)
Dim tweetXML As XmlDocument = utils.GetXMLForURL(listURL)
Dim tweetnodelist As XmlNodeList = tweetXML.ChildNodes(1).ChildNodes
For Each node As XmlNode In tweetnodelist
Dim tweet As New SimpleTweet
tweet.CreatedAt = node.SelectSingleNode("created_at").InnerText
tweet.HTMLText = utils.ReturnTextWithHRefLink(node.SelectSingleNode("text").InnerText)
tweet.ID = node.SelectSingleNode("id").InnerText
tweet.Name = node.SelectSingleNode("user/name").InnerText
tweet.ScreenName = node.SelectSingleNode("user/screen_name").InnerText
tweet.Text = node.SelectSingleNode("text").InnerText
tweet.UserID = node.SelectSingleNode("user/id").InnerText
tweet.ProfileImageURL = node.SelectSingleNode("user/profile_image_url_https").InnerText
result.Add(tweet)
Next
Next
sortedresult = result.OrderByDescending(Function(tweet) tweet.ID)
End If
Return sortedresult
End Function
You need to materialize the result with a call to .ToList(). Add it to the end of this line:
sortedresult = result.OrderByDescending(Function(tweet) tweet.ID)
sortedResult is of type List(Of SimpleTweet) and OrderByDescending returns an IOrderedEnumerable(Of SimpleTweet) that cannot automatically be cast to the expected type.
Since you want to return a List(Of SimpleTweet) you need to call ToList to create a new list from the IEnumerable(Of SimpleTweet):
Return sortedresult.ToList()
ToList forces an immediate query evaluation.
I need to set a default value for the DropDown list as follows:
#Html.DropDownList("BillId", "")
The user doesn't necessarily need to select something but the list throws an error
The ViewData item that has the key 'BillId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
if a value is not selected and the box is left on it's default blank state.
My controllers as follows:
Function Create(id As Integer) As ViewResult
ViewBag.id = id
Dim job As Job = New Job
job.CustomerId = id
job.JobAmount = 0
job.JobDate = Date.Now()
job.JobStatus = "Active"
Dim BillList = New List(Of Bill)()
Dim BillQuery = From s In db.Bills
Select s
BillList.AddRange(BillQuery)
ViewBag.BillId = New SelectList(BillList, "BillId", "BillDate")
Return View(job)
End Function
'
' POST: /Job/Create
<HttpPost()>
Function Create(job As Job) As ActionResult
If ModelState.IsValid Then
db.Jobs.Add(job)
db.SaveChanges()
Dim customer As Customer = db.Customers.Find(job.CustomerId)
Dim customerNumber As String = customer.CustCellphone.ToString()
Dim messageSender As SendMessage = New SendMessage
Dim smsMessage As String = "LAUNDRY: Job Number " & job.JobId & " has been booked in. You will be notified when individual services within it are ready for collection."
messageSender.SendMessage(smsMessage, customerNumber)
Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
Return Redirect(url)
End If
Return View(job)
End Function
If your model Job doesn't have the property of BillId than in the view the dropdown markup should be
#Html.DropDownList("Job_BillId", ViewBag.BillId)
And the model Job contains the property BillId than create the ViewBag with some different name and use them accordingly in view markup for example:
Create a ViewBag with different name instead of BillId in controller
ViewBag.BillIdList = New SelectList(BillList, "BillId", "BillDate")
And in view use this as below
#Html.DropDownListFor(model => model.BillId, ViewBag.BillIdList)
Hope this will help you.